原生JavaScript實現Ajax的方法_javascript技巧

來源:互聯網
上載者:User

首先為大家分享了原生JavaScript實現Ajax代碼,供大家參考,具體內容如下

var getXmlHttpRequest = function() {  if (window.XMLHttpRequest) {    //主流瀏覽器提供了XMLHttpRequest對象    return new XMLHttpRequest();  } else if (window.ActiveXObject) {    //低版本的IE瀏覽器沒有提供XMLHttpRequest對象    //所以必須使用IE瀏覽器的特定實現ActiveXObject    return new ActiveXObject("Microsoft.XMLHttpRequest");  }};var xhr = getXmlHttpRequest();xhr.onreadystatechange = function() {  console.log(xhr.readyState);  if (xhr.readyState === 3 && xhr.status === 200) {    //擷取成功後執行操作    //資料在xhr.responseText    console.log(xhr.responseText);  }};xhr.open("get", "data.php", true);xhr.send("");

下面和大家分享幾種利用javascript實現原生ajax的方法。
實現ajax之前必須要建立一個 XMLHttpRequest 對象。如果不支援建立該對象的瀏覽器,則需要建立 ActiveXObject,具體方法如下:

var xmlHttp; function createxmlHttpRequest() { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp=new XMLHttpRequest(); } 

(1)下面使用上面建立的xmlHttp實現最簡單的ajax get請求:

function doGet(url){ // 注意在傳參數值的時候最好使用encodeURI處理一下,以防出現亂碼 createxmlHttpRequest(); xmlHttp.open("GET",url); xmlHttp.send(null); xmlHttp.onreadystatechange = function() { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert('success'); } else { alert('fail'); } } } 

(2)使用上面建立的xmlHttp實現最簡單的ajax post請求:

function doPost(url,data){ // 注意在傳參數值的時候最好使用encodeURI處理一下,以防出現亂碼 createxmlHttpRequest(); xmlHttp.open("POST",url); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(data); xmlHttp.onreadystatechange = function() { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert('success'); } else { alert('fail'); } } } 

以上就是本文的全部內容,希望對大家的學習有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.