原始的ajax的操作
var onSuccess = function(result){}; //成功的回调
var onFail = function(error){}; //失败的回调
var xhr = new XMLHttpRequest();
xhr.open("POST", "www.baidu.com", true);
xhr.onload = function(){
if(xhr.readyState === 4 && xhr.status === 200){
onSuccess(xhr.response);
} else {
onFail(xhr.statusText);
}
}
xhr.onerror = function(){
onFail(Error("网络异常"));
}
XMLHttpRequest对象常用属性:
(1)onreadystatechange:用于设置事件处理函数;
(2)readystate:用于返回Ajax请求的处理状态,readystate属性共有5种取值:
(3)status:用于返回服务器处理HTTP状态码;
(4)responseText和responseXML:用于获取服务器对HTTP请求的响应内容。如果响应内容是普通文本字符串则是第一个,如果是XML格式的则为第二个。
用promise封装后:
function queryData (url){
var p = new Promise(function(resove,reject){
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readystate == 4&&xhr.status==200) {
resove('xhr.responseText');
}else{
reject('服务器错误');
}
}
xhr.open('get',url);
xhr.send();
})
return p;
}
Promise常用实例方法:
(1)then(),用于得到正确的返回结果
(2)catch(),获取异常信息,具体用法与上面代码中then()方法一致。