创建XHR对象

兼容IE7已经更高的版本:

function createXHR(){
   if(typeof XMLHttpRequest != "undefind"){
       return new XMLHttpRequest();    
    }else if(typeof ActiveXObject != "undefind"){
        var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],
             len = versions.length;
         for(var i = 0; i < len; i ++){
             try{
                 new ActiveXObject(versions[i]);
                 arguments.callee.activeXString = versions[i];
                 break;
             }catch(e){
                  console.log(e);
            }
         }
    }else{
        throw new Errow("NO XHR object");
    }
}        

  

var xhr = createXHR();

 

XHR的用法

方法:

1. open()

启动一个请求必备发送:

xhr.open("get", "demo.php", false);

  三个参数:

  • 请求的类型 get / post
  • url
  • 同步(false)或者异步(true),  默认为异步        

2. send()

请求发送服务器:

xhr.send(null)

 

 

属性:

 

1. responseText

  从服务器返回的文本

2. responseXML

  

3. status

  相应的HTTP状态

  

4. statusText

  HTTP状态的说明

 

同步情况下可以:

xhr.open("get", "demo.php", false);
xhr.send(null);

if(xhr.status >=200 && xhr.status < 300 || xhr.status == 304){
   console.log(xhr.responseText);
}else{
   console.log("Request was unsuccessful: " + xhr.status );
}

  

一般我们都是异步:

var xhr = createXHR();

xhr.onreadystatuschange = function(){
  if(xhr.readyStatus == 4){
     if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
        console.log(xhr.responseText);
    }else{
        console.log("Request was unsuccessful: " + xhr.status);
    }
  }      
};

xhr.open("get", "demo", true);
xhr.send(null);

  

 

请求方式

1. GET

参数的拼接:

 url + "?" + "名1=值1" + "&" + "名2=值2" + .....

xhr.open("get", "demo.php?name1=value1&name2=value2", true);

  

 

2. POST

 

 

 

 

  

posted on 2017-12-12 15:31  dengaye  阅读(341)  评论(0编辑  收藏  举报