標籤:
即 Asynchronous [e‘s??kr?n?s] Javascript And XML,AJAX 不是一門的新的語言,而是對現有技術的綜合利用。
本質是在HTTP協議的基礎上以非同步方式與伺服器進行通訊。
XMLHttpRequest可以以非同步方式的處理常式,瀏覽器內建對象,用於在後台與伺服器通訊(交換資料) ,由此我們便可實現對網頁的部分更新,而不是重新整理整個頁面。
封裝ajax工具函數
$.ajax = function(options){
if(!options) return false;
/*options 參數傳遞*/
var type = options.type || ‘get‘;
var url = options.url || location.pathname;
var async = options.async === false ? false : true;
var data = options.data || {};
/*data 選要轉化成 name=xjj&age=10*/
var dataStr = ‘‘;
for(var key in data){
//console.log(data[key]);
dataStr += key+‘=‘+data[key]+‘&‘;
}
/*如果就資料 就裁剪掉最後一個&*/
dataStr = dataStr && dataStr.slice(0,-1);
/*ajax 編程*/
/*初始化*/
var xhr = new XMLHttpRequest();
/*請求行*/
/*如果是get請求那麼就要拼接資料在url後面 ?*/
xhr.open(type,type == ‘get‘?url+‘?‘+dataStr:url,async);
/*要求標頭*/
/*如果是post請求需要設定 content-type application/x-www-form-urlencoded*/
if(type == ‘post‘){
xhr.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);
}
options.beforeSend && options.beforeSend();
/*請求主體*/
/*如果是post請求需要把資料字元傳過去 否則是null*/
xhr.send(type==‘get‘?null:dataStr);
/*監聽響應狀態的改變*/
xhr.onreadystatechange = function(){
/*響應成功*/
if(xhr.readyState == 4){
if( xhr.status == 200){
/*處理響應成功函數*/
var result = ‘‘;
/*接受資料*/
/* json xml string*/
var contentType = xhr.getResponseHeader(‘Content-Type‘);
if(contentType.indexOf(‘xml‘) > -1){
/*服務端返回的是xml資料格式*/
result = xhr.responseXML;
}else if(contentType.indexOf(‘json‘) > -1){
/*服務端返回的是json資料格式*/
/*json字串*/
var str = xhr.responseText;
result = JSON.parse(str);
}else{
result = xhr.responseText;
}
/*調用回呼函數*/
options.success && options.success(result);
}
/*響應失敗*/
else{
/*處理響應失敗函數*/
options.error && options.error(‘request fail code‘ + xhr.status);
}
options.complete && options.complete();
}
}
};
AJAX編程-封裝ajax工具函數