1.封装函数
function ajax(options) {
options = options || {
};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "json";
options.async=options.async|| true;
var params = formatParams(options.data);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if(window.ActiveObject) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var status = xhr.status;
if (status >= 200 && status < 300 || status == 304) {
options.success(xhr.responseText);
} else {
options.error(status);
}
}
}
if (options.type == "GET") {
xhr.open("GET", options.url + "?" + params, options.async);
xhr.send(null);
} else if (options.type == "POST") {
xhr.open("POST", options.url, options.async);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
return arr.join("&");
}
}
2.封装函数的使用实例
ajax({
url:"https://server/login",
type:'post',
data:{
user:'username', pass:'password' },
dataType:'json',
success:function(data){
},
error:function(err){
console.log(err);
}
})