$ = {
ajax:function(options){
var xhr = null, // XXMLHttpRequest對象
url = options.url, // url 地址
method = options.method || 'GET', // 傳輸方式,默認GET
async = typeof (options.async) === "undefined"?true:options.async,
data = options.data || null,
params = '', //傳遞的參數
callback = options.success,
error = options.error;
// 將data的對象字面量的形式轉化為字符串形式
if(data){
for(var i in data){
params += i + '=' + data[i] + '&';
}
params = params.replace(/&$/,'');
}
// 根據method 的值改變URL
if(method === 'GET'){
url += '?' + params;
}
if(typeof XMLHttpRequest != "undefined"){
xhr = new XMLHttpRequest();
}else if(typeof ActiveXObject != "undefined"){
var xhrArr = ['Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP.2.0',]
var len = xhrArr.length;
for(var i=0; i <=len; i++){
try{
xhr = new ActiveXObject(xhrArr[i])
break
}catch(e){
//TODO handle the exception
}
}
}else{
throw new Error('No XHR object available.');
}
xhr.onreadystatechange = function(){
if xhr.readyState === 4){
if((xhr.status >=200 && xhr.status <300) || xhr.status===304){
callback && callback(JSON.parse(xhr.responseText))
}else{
error && error();
}
}
}
// 創建發送請求
xhr.open(method,url,async)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。