用原生JS對AJAX做簡單封裝的執行個體代碼_javascript技巧

來源:互聯網
上載者:User

首先,我們需要xhr對象。這對我們來說不難,封裝成一個函數。

var createAjax = function() { var xhr = null; try { //IE系列瀏覽器 xhr = new ActiveXObject("microsoft.xmlhttp");  } catch (e1) { try { //非IE瀏覽器 xhr = new XMLHttpRequest();    } catch (e2) { window.alert("您的瀏覽器不支援ajax,請更換!");    }  } return xhr;}; 

然後,我們來寫核心函數。

var ajax = function(conf) { // 初始化 //type參數,可選 var type = conf.type; //url參數,必填 var url = conf.url; //data參數可選,只有在post請求時需要 var data = conf.data; //datatype參數可選 var dataType = conf.dataType; //回呼函數可選 var success = conf.success; if (type == null){ //type參數可選,預設為get type = "get";  } if (dataType == null){ //dataType參數可選,預設為text dataType = "text";  } // 建立ajax引擎對象 var xhr = createAjax(); // 開啟 xhr.open(type, url, true); // 發送 if (type == "GET" || type == "get") {    xhr.send(null);  } else if (type == "POST" || type == "post") {    xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");    xhr.send(data);  }  xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if(dataType == "text"||dataType=="TEXT") { if (success != null){ //普通文本 success(xhr.responseText);        }      }else if(dataType=="xml"||dataType=="XML") { if (success != null){ //接收xml文檔 success(xhr.responseXML);        }       }else if(dataType=="json"||dataType=="JSON") { if (success != null){ //將json字串轉換為js對象 success(eval("("+xhr.responseText+")"));        }      }    }  };}; 

最後,說明一下此函數的用法。

 ajax({ type:"post",    url:"test.jsp",    data:"name=dipoo&info=good",    dataType:"json",    success:function(data){ alert(data.name); } }); 

以上這篇用原生JS對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.