Ajax之XMLHttpRequest


function createXHR(){
    if(typeof XMLHttpRequest !="undefined"){
        return new XMLHttpRequest;
    }
    //兼容IE7及之前的版本,如果不考虑兼容,可不写
    else if(typeof ActiveXObject !="undefined"){
        if(typeof arguments.callee.ActiveXObject !="undefined"){
            var versions =["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"];
            var i,len;
            for(i=0;i<versions.length;i++){
                try{
                    new ActiveXObject(versions[i]);
                    arguments.callee.activeXstring=versions[i];
                }catch(e){
                    //TODO handle the exception
                }
            }
        }
        return  new ActiveXObject(arguments.callee.activeXstring);
    }//else if
    else{
        throw new Error("no XHR object available");
    }
}

var xhr =createXHR();

//要调用的第一个方法    open(请求类型,请求地址,是否异步)

xhr.open('get','text.txt',false);
xhr.send();//请求主体发送的数据

/*
 1.当请求为同步时,JavaScript代码会等到服务器响应后才继续执行

在接收到响应后,响应的数据会自动填充  XHR对象的属性相关属性如下
xhr.responseText:作为响应主体被返回的文本

xhr.responseXML:
如果响应的内容类型是 text/xml   application/xml,
将返回 XML DOM文档

xhr.status:响应的HTTP状态
xhr.statusText:HTTP状态说明

2.在接收到响应后,第一步是检查status属性,状
态码为200则表示成功
此时,responseText内容已经可以访问了

304 表示请求的资源没有被修改,可直接使用浏览器中缓存的版本
因此,为确保接收到适当的响应,应该检查状态码
 */
if((xhr.status>=200&&xhr.status<300||xhr.status ==304)){
    console.log(xhr.responseText);
}
else{
    console.log("error"+xhr.status)
}





open(method,url,async);

规定请求的类型、URL 以及是否异步处理请求。
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)

send(string)
将请求发送到服务器。
string:仅用于 POST 请求

GET请求

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    <div id="myDiv"></div>
    </body>
    <script>
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        console.log(xmlhttp);
    document.getElementById("myDiv").innerHTML=xmlhttp.response;
    /*
    如果您希望通过 GET 方法发送信息,请向 URL 添加信息:
    防止缓存可加上一个随机数之类的
    xmlhttp.open("GET","server.txt?t="+Math.random(),true);
    */
    }
  }
xmlhttp.open("GET","server.txt",true);
xmlhttp.send();
    </script>
</html>

POST请求

setRequestHeader(header,value)

向请求添加 HTTP 头。
header: 规定头的名称
value: 规定头的值

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
  //GET改为POST就行了
xmlhttp.open("POST","/ajax/demo_post.asp",true);
/*
如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
*/
xmlhttp.send();

服务器响应

responseText 获得字符串形式的响应数据。
responseXML 获得 XML 形式的响应数据。

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;


xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
  {
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;

onreadystatechange 事件

onreadystatechange

存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status
200: “OK”
404: 未找到页面

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

使用 Callback 函数
优点就是可将获得数据传到AJax函数外面,使其他函数也可以调用数据

var xmlhttp;
function loadXMLDoc(url,cfunc)//cfunc就是---calback函数
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.onreadystatechange=cfunc;
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("/ajax/test1.txt",function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  });
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值