前後端資料互動ajax
ajax是異步JavaScript和XML;主要用于前後端資料互動,通過在背景與伺服器進行少量資料交換,AJAX 可以使網頁實作異步更新。這意味着可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。
如何建立ajax?
- 建立ajax對象
考慮相容建立ajax對象
if(window.XMLHttpRequest){
//ie6+
var oAjax = new XMLHttpRequest();
}else{
//ie6
var oAjax = new ActiveXObject('Microsoft.XMLHTTP');
}
- 打開位址
//GET和POST方法
oAjax.open('GET',URL+'?'+拼接好的資料,true);
oAjax.open('POST',URL,true);
- 資料的送出方式
一般采用GET和POST送出資料
//GET方法送出
oAjax.send();
//POST方法送出(需要設定請求頭)
oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
oAjax.send(json2url(json.data));
- 接收資料
oAjax.onreadystatechange=function(){
if(oAjax.readyState==){
if(oAjax.status>= && oAjax.status< || oAjax.status==){
//資料
oAjax.responseText
}else{
//擷取失敗傳回http狀态碼
oAjax.status
}
}
};
下面進行具體的封裝:
//拼接資料的函數,後面加了時間戳用于防止緩存
function json2url(json){
var oDate=new Date();
json.t=oDate.getTime();
var arr=[];
for(var name in json){
arr.push(name+'='+json[name]);
};
return arr.join('&');
}
//url,data,type,fnSucc,fnFail,loading
function ajax(json){
json=json || {};
json.data=json.data || {};
json.type=json.type || 'get';
json.time=json.time || ;
if(!json.url){
return;
}
//建立ajax對象 相容ie6
if(window.XMLHttpRequest){
var oAjax=new XMLHttpRequest();
}else{
var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
}
//判斷資料發送方式
switch(json.type.toLowerCase()){
case 'get':
oAjax.open('GET',json.url+'?'+json2url(json.data),true);
oAjax.send();
break;
case 'post':
oAjax.open('POST',json.url,true);
//post方法要設定請求頭
oAjax.setRequestHeader('content-type','application/x-www-form-urlencoded');
oAjax.send(json2url(json.data));
break;
}
//資料加載時可加入loading函數
json.loading && json.loading();
//資源加載情況
oAjax.onreadystatechange=function(){
if(oAjax.readyState==){
//http狀态碼
if((oAjax.status>=&&oAjax.status<)||oAjax.status==){
json.success&&json.success(oAjax.responseText);
}else{
json.fail&&json.fail(oAjax.status);
}
json.complete && json.complete();
clearTimeout(timer);
}
};
var timer=null;
//一定時間資料取不會來則提示資訊
timer=setTimeout(function(){
alert('請求逾時');
oAjax.onreadystatechange=null;
},json.time)
}
//調用
ajax({
url:URL,
data:{資料(json格式)},
type:post/get,
loading:function(){},
success:function(){},
fail:function(){},
})