有時候在做開發的時候,會用到js但是做的頁面卻不能引用jQuery,擔心會和別的jQuery版本衝突。所以就自己封裝一個原生的ajax來使用 。
function ajax(options) {
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "json";
var params = formatParams(options.data);
//創建 - 非IE6 - 第一步
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else { //IE6及其以下版本瀏覽器
var xhr = 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);
}
}
}
//連接 和 發送 - 第二步
if (options.type == "GET") {
xhr.open("GET", options.url + "?" + params, true);
xhr.send(null);
} else if (options.type == "POST") {
xhr.open("POST", options.url, true);
//設置表單提交時的內容類型
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
xhr.send(params);//==============================
}
}
//格式化參數
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("&");
}
在js裏使用的調用
function findService()
{
ajax({
url: "xxxxxxx", //請求地址
type: "POST", //請求方式
dataType: "json", //數據格式
success: function (response) {
var array = eval(response);
//執行成功的代碼
},
fail: function (status) {
//執行失敗的代碼
}
});
}