天天看點

javascript異步請求的幾種方式

第一種,基本方法。這種方法比較基礎,而且可以根據readyState和status的不同狀态,寫不同的處理代碼。算是比較完備的吧。

var xmlHttp;

if (window.ActiveXObject) {

   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} else {

   if (window.XMLHttpRequest) {

    xmlHttp = new XMLHttpRequest();

   }

}

//設定屬性

xmlHttp.onreadystatechange = getPreRespons;

xmlHttp.open("POST", url, true);

//post方法必須設定這個請求頭

xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    //發送請求 

xmlHttp.send(params);

//獲得傳回資料

function getPreRespons() {

//alert(xmlHttp.readyState);

if (xmlHttp.readyState == 4) {

//alert(xmlHttp.status)

   if (xmlHttp.status == 200) {

    parsePrem();//這個方法的代碼略去,自己寫就行

第二種,這種方法要先引入prototype.js。這種方法算是半封裝,因為他封裝了基本的一些代碼,如設定屬性等;但是将onComplte等 方法暴露了出來。更具體的方面,我另寫有文章。

var myAjax = new Ajax.Request(

    url,

    {method:'post',parameters:params,onComplete: processResponse,asynchronous:true});

第三種,是jquery的方法,是以要先引入jquery.js。這種方法封裝得比較厲害,隻留了一個omCompleted方法出來。不過 jquery也留了底層方法,可以通過使用底層方法來擷取更大的程式設計靈活性。不知道prototype有沒有類似的方法。

jQuery.post(action, params, onCompleted, "text");

本文轉自 斯然在天邊 51CTO部落格,原文連結:http://blog.51cto.com/winters1224/799027,如需轉載請自行聯系原作者

繼續閱讀