AJAX說明
- IE7及其以上版本中支持原生的 XHR 對(duì)象,因此可以直接用:new XMLHttpRequest();
- IE6及其之前的版本中,XHR對(duì)象是通過MSXML庫中的一個(gè)ActiveX對(duì)象實(shí)現(xiàn)的。則:new ActiveXObject('Microsoft.XMLHTTP');
實(shí)現(xiàn)
function ajax(options) {
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.async = options.async || true;
var params = formatParams(options.data);
//若IE9以上,支持ES5,則可用以下方法快捷格式化參數(shù)
//var qs = Object.keys(data).reduce(function(pre,cur,index){
// return pre + '&' + encodeURIComponent(cur) + '=' + encodeURIComponent(data[cur]);
//},'');
//var params = qs.slice(1);
//創(chuàng)建xhr - 非IE6/IE6及其以下版本瀏覽器
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//接收 - 第三步
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var status = xhr.status;
if (status >= 200 && status < 300) {
options.success && options.success(xhr.responseText, xhr.responseXML);
} else {
options.fail && options.fail(status);
}
}
}
//連接 和 發(fā)送 - 第二步
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);
//設(shè)置表單提交時(shí)的內(nèi)容類型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
}
//格式化參數(shù)
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
arr.push(("v=" + Math.random()).replace(".", ""));
return arr.join("&");
}
//調(diào)用方法
ajax({
url: "url", //請(qǐng)求地址
type: "POST", //請(qǐng)求方式
data: { a: "test", b: "t" }, //請(qǐng)求參數(shù)
success: function (response, xml) {
// 此處放成功后執(zhí)行的代碼
},
fail: function (status) {
// 此處放失敗后執(zhí)行的代碼
}
});
大前端知識(shí)庫收集分享 www.rjxgc.com 壹玖零Tech
搜羅各種前后端奇淫技巧,花式編程思想,日日更新,速來圍觀吧...