原生JavaScript 封裝ajax

來源:互聯網
上載者:User

標籤:.com   asc   new   字元   javascrip   字串   code   對象   href   

function myajax(options){
//建立一個局部對象 用來存放使用者輸入的各種參數
var opt={
type:options.type||"get",//擷取使用者輸入的傳輸方法,可選,不寫為get
data:options.data||"",//擷取使用者輸入的資料
dataType:options.dataType||"",//擷取使用者輸入的資料類型比如json 或者xml
url:options.url||"",//使用者輸入的url
success:options.success||null//成功函數。
}

if(opt.url==""){//如果使用者沒有輸入URL,這樣是不允許的 。直接返回,不執行以後的操作
alert("url不可為空");
return;
}
if(options.type){
opt.type=options.type.toLowerCase();//將使用者輸入的POST等方法變成小寫
}
//建立一個連線物件。標準瀏覽器中 都建立XMLHttpRequest 對象。非標準的瀏覽器中建立ActiveXObject
var xhr=null;
try{
xhr=new XMLHttpRequest;
}catch(e){
xhr=new ActiveXObject("Micsoft.XMLHTTP");
}
//如果使用者用get方法,則需要拼接URL,將使用者的資料放到URL傳到後台
if(opt.type=="get"&&opt.data){
opt.url+="?"+opt.data;
}
xhr.open(opt.type,opt.url,true);//調用xhr.open方法串連後台借口
//如果是get方法,則send函數不傳值、
if(opt.type="get"){
xhr.send(null);
}else{
//如果是post方法 則需要加一個串連頭。且send函數中 傳入使用者的資料
xhr.setRequestHeader(‘content-type‘,‘application/x-www-form-urlencoded‘);
xhr.send(opt.data);
}
//串連完畢,等後台返回結果和資料
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//readyState有5種狀態代碼。0,1,2,3,4
if(xhr.status==200){//http狀態代碼為200代表成功
var data=xhr.responseText;//建立一個變數儲存後台返回的資料
if(opt.dataType.toLowerCase()=="xml"){
data=xhr.responseXML;//如果後台返回的XML格式的資料.用responseXML來擷取
}
if(opt.dataType.toLowerCase()=="json"){
data=JSON.parse(data);//如果是json 則用parse來將字串轉化為對象
}
if(typeof opt.success===‘function‘){
opt.success(data);//如果有成功的回呼函數 則將後台資料當做回呼函數的參數返回過去
}
}else{
alert("出錯啦"+xhr.status)//如果狀態代碼不為200,串連失敗,返回http狀態代碼
}

}

}
}

 

補充:

readyState的狀態代碼含義

0:請求未初始化

1:伺服器串連已建立

2:請求已接受

3:請求處理中

4:請求完成,且響應就緒。

原生JavaScript 封裝ajax

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.