cc icon indicating copy to clipboard operation
cc copied to clipboard

3. XMLHttpRequest对象

Open ccforward opened this issue 9 years ago • 0 comments

从 Ajax 入手理解 XMLHttpRequest 对象

先写一个完整的Ajax请求

// 创建XMLHttpRequest对象
function xhr(){
    var xhr;
    try {
        xhr = new XMLHttpRequest();
    }catch(e){
        try{
            xhr = new ActiceXObject('Msxml2.XMLHTTP');
        }catch(e){
            try{
                xhr = new ActiveXObject('Microsoft.XMLHTTP');
            }catch(e){
                alert('不支持 ajax');
                return fasle;
            }
        }
    }
    return xhr;
}
/** 发送Ajax请求
 * url:请求地址
 * methodType: GET,POST,HEAD 请求方式
 * sycn: true,false 同步或异步
 * callback 回调
 * obj 回调中要处理的对象
 */
function ajaxRequest(url,methodType,sycn,callback,obj){
    var xhr = xhr();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                obj.result = xhr.responseText;
                console.log(xhr);
                callback(obj);
            }               
        }           
    }
    xhr.open(methodType,url,sycn);
    xhr.send(null);
}

XMLHttpRequest的属性

  • onreadystatechange: function
    当readyState属性发生变化时会调用
  • readyState
    0:未打开,open()方法未调用
    1:未发送,send()方法未调用
    2:以获取响应头,send()方法已调用,响应头响应状态已经返回
    3:正在下载响应体,responseText中已获取部分数据
    4:请求完成,整个请求已经完毕
  • status [只读]请求响应的状态码 例如 200,500 ,404
  • statusText [只读]请求响应的状态码的状态信息 200:OK
  • responseType 改变响应类型,告诉服务器期望的响应格式。
    "": 返回字符串(默认)
    "arraybuffer": 返回ArrayBuffer
    "blob": Blob
    "document": Document
    "json": JSON字符串
    "text": 字符串
  • responseText
    本次响应为文本
  • responseXML [只读]本次响应为一个DOM对象,或者null。

XMLHttpRequest的方法

  • open 初始化一个请求
  • send 发送请求
  • abort 如果请求已被发送,则立即中断请求。返回响应的头信息或null
  • setRequestHeader() 给指定的HTTP请求头赋值;赋值前必须已经调用了open()打开了一个URL

ccforward avatar Dec 13 '14 07:12 ccforward