function ajax(options){
// 1.處理默認參數
var {type,url,success,error,data,timeout} = options;
type = type || "get";
data = data || {};
timeout = timeout || 2000;
// 2.解析要發送的數據
var str = "";
for(var i in data){
str += `${i}=${data[i]}&`;
}
// 3.根據方式,決定是否處理url
if(type == "get"){
var d = new Date();
url = url + "?" + str + "__qft=" + d.getTime();
}
// 4.開啟ajax
var xhr = new XMLHttpRequest();
// 注意:open中的方式
xhr.open(type,url,true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
// 5.執行成功之前,先判斷是否傳入
success && success(xhr.responseText);
// 成功之后,不應有失敗
error = null;
}else if(xhr.readyState == 4 && xhr.status != 200){
// 6.執行失敗之前,先判斷是否傳入
error && error(xhr.status);
// 失敗之后,不應有成功
success = null;
// 且失敗不應多次執行
error = null;
}
}
// 7.如果請求超時,執行失敗
setTimeout(() => {
error && error("timeout");
// 失敗之后,不應有成功
success = null;
}, timeout);
// 8.最后根據type的方式,決定send的發送內容和格式
if(type == "post"){
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(str)
}else{
xhr.send()
}
}