XMLHttpRequest对象
XMLHttpRequest 对象提供了对 HTTP 协议的完全的访问,包括做出 POST 和 HEAD 请求以及普通的 GET 请求的能力。
XMLHttpRequest 对象是Ajax请求的基础。
AJAX请求
var xhr = new XMLHttpRequest();
xhr.open('get/post', 'url地址', 'ture/false'); // 请求方式/地址/是否异步
xhr.send(null);
//监听状态改变和接收数据
xhr.onreadystatechange = function() {
//readyState == 4 发送完成
//status >= 200 接收完成
if(xhr.readyState == 4 && xhr.status == 200) {
var data = xhr.responseText;
}
}
封装一个兼容的AJAX请求
function createXHR() {
if(window.XMLHttpRequest) {
return new XMLHttpRequest();
}
return new ActiveXObject(); //IE6-
}
//obj {name:huhu,age:18} => "name=huhu&age=18"
function params(obj) {
var arr = [];
for(var i in obj) {
var str = i + "=" + obj[i];
arr.push(str);
}
return arr.join("&");
}
function ajax(obj) {
var xml = createXHR();
obj.data = params(obj.data);
//get请求把参数添加到url后面
if(/get/i.test(obj.method)) {
obj.url += obj.data.length > 0 ? ("?" + obj.data) : "";
}
xhr.open(obj.method, obj.url, obj.async);
if(/get/i.test(obj.mothod)) {
xml.send(null);
} else {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(obj.data);
}
if(obj.async) {
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
callback();
}
}
} else {
callback(); //同步
}
function callback() {
if(xhr.status == 200) {
obj.success(xhr.responseText);
} else {
obj.error(xhr.status);
}
}
}
//使用
ajax({
method: 'xxx',
url: 'XXX'
params: {
name: huhu,
age: 18
},
async: true
})