欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ajax的get与post方式

程序员文章站 2022-03-02 13:48:18
...
 <script type="text/javascript">
    //获取a节点并为其添加onclick 相应方法
    window.onload = function(){
        document.getElementsByTagName("a")[0].onclick = function(){
            //3.创建XMLHttpRequest对象
            var request = new XMLHttpRequest();
            //4.准备发送请求的数据: url
            var url = this.href + "?time=" + new Date();//加时间戳抑制缓存
            var method = "GET";
            //var method = "POST";//post

            //5.调用XMLHttpRequest对象的open方法
            request.open(method, url);

            //request.setRequestHeader("ContentType","application/x-www-form-urlencoded");//post

            //6.调用XMLHttpRequest对象的send方法
            request.send(null);
            //request.send("name='whiteblack'");//post

            //7.为XMLHttpRequest对象添加onreadystatechange 响应函数
            request.onreadystatechange = function(){
            //8.判断响应是否完成readyState = 4
                if(request.readyState == 4){
                //9.判断响应status = 200
                    if(request.status == 200 || request.status == 304){
                    //10.打印响应结果 responseText
                        alert(request.responseText);
                        }
                }
            }

        }

        //2.取消a节点的默认行为
        return false;
    }

  </script>

  <body>
    <a href="mes.txt">hello AJAX!</a>
  </body>
</html>