原生js实现ajax
xhr 具有以下常用属性:
responseText: 请求返回的数据内容
responseXML: 如果响应内容是"text/xml""application/xml",这个属性将保存响应数据的 XML DOM文档
status: 响应的HTTP状态,如 200 304 404 等
statusText: HTTP状态说明
readyState: 请求/响应过程的当前活动阶段
timeout: 设置请求超时时间
-
xhr.readyState==0 尚未调用 open 方法
-
xhr.readyState==1 已调用 open 但还未发送请求(未调用 send)
-
xhr.readyState==2 已发送请求(已调用 send)
-
xhr.readyState==3 已接收到请求返回的数据
-
xhr.readyState==4 请求已完成
function get(url,data,callback){
let paramArr = [];
let encodeData;
if (data instanceof Object) {
for (let key in data) {
// 参数拼接需要通过 encodeURIComponent 进行编码
paramArr.push( encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) )
}
encodeData = paramArr.join('&')
}
url += encodeData;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
//如果是IE5或者IE6浏览器,则使用ActiveX对象
xhr = ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('GET',url,true)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status == 200 || xhr.status == 304){
callback(response)
}
}
xhr.send(null)
}
function post(url,data,callback){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
//如果是IE5或者IE6浏览器,则使用ActiveX对象
xhr = ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST',url,true)
xhr.setRequestHeader('Content-Type':"application/x-www-form-urlencoded")
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200 || xhr.status === 304){
callback(response)
}
}
xhr.send(data)
}