$ = {
ajax:function(options){
var xhr = null, // XXMLHttpRequest對(duì)象
url = options.url, // url 地址
method = options.method || 'GET', // 傳輸方式,默認(rèn)GET
async = typeof (options.async) === "undefined"?true:options.async,
data = options.data || null,
params = '', //傳遞的參數(shù)
callback = options.success,
error = options.error;
// 將data的對(duì)象字面量的形式轉(zhuǎn)化為字符串形式
if(data){
for(var i in data){
params += i + '=' + data[i] + '&';
}
params = params.replace(/&$/,'');
}
專(zhuān)注于為中小企業(yè)提供成都網(wǎng)站制作、做網(wǎng)站服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)三江侗免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了上千家企業(yè)的穩(wěn)健成長(zhǎng),幫助中小企業(yè)通過(guò)網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
// 根據(jù)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();
}
}
}
// 創(chuàng)建發(fā)送請(qǐng)求
xhr.open(method,url,async)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
}
}