2011-06-27 25 views
0

我通常在JavaScript中像這樣構建腳本或類似的東西,當腳本依賴於某些ajax或服務器響應時。我真的不覺得這是做事最有效的方式,那麼做這些類型的腳本會更好?如何製作一個高效的基於Ajax的javascript腳本

function someclass() { 

    //some internal variables here 
    this.var1 = null; 
    this.var2 = null; 
    ... 

    //some ajax function which gets some critical information for the other functions 
    this.getAJAX = function() { 
     self = this; 
     urls = "someurlhere"; 
     //jquery ajax function 
     $.ajax({ 
      type: "GET", 
      url: url, 
      dataType: 'json', 
      complete: function (xhr, textStatus) { 
       //get the response from the server 
       data = JSON.parse(xhr.responseText); 
       //call the function which will process the information 
       self.processAJAX(data); 
      } 
     }) 

    this.processAJAX = function(data) { 
     //set some of the internal variables here 
     //according to the response from the server 

     //now that the internal variables are set, 
     //I can call some other functions which will 
     //use the data somehow 
     this.doSomething(); 
    } 

    this.doSomething = function() { 
     //do something here 
    } 

} 

所以我使用的腳本是這樣的:

//instantiate the class 
foo = new someClass(); 

//get the information from the server 
//and the processAjax function will eventually 
//call the doSomething function 
foo.getAjax(); 

所以,我真的不喜歡這個,因爲它不是在使用發生了什麼腳本的清晰。我希望能夠做這樣的事情:

//instantiate the class 
foo = new someClass(); 

//get info from the server 
//in this example, the processAJAX function will not call the doSomething 
foo.getAjax(); 

//do something 
foo.doSomething(); 

然而,這並不工作,因爲通常來自服務器的響應需要一些時間,所以當DoSomething的是所謂的,必要的信息現在還沒有,因此,該功能不會做它想要做的事情。

如何使這項工作?

我相信答案已經在StackOverflow的某個地方,但是我找不到任何東西,所以我會很感激這兩個,無論是答案或鏈接到一個資源,這將解釋這一點,可能在StackOverflow。任何幫助表示讚賞。謝謝。

回答

2

標準模式是接受一個回調函數給你的異步方法,這個類負責在操作完成時調用它。

function someclass() { 
    this.getAJAX = function(callback) { 
     this.afterAJAXCallback = callback; 
     ... 
    }); 

    this.processAJAX = function(data) { 
     ... 
     if (this.afterAJAXCallback) this.afterAJAXCallback(); 
    } 
} 

然後你可以使用閉包回調到位,組織你的代碼,很多在你使用時的方式jQuery的$。阿賈克斯:

foo = new someClass(); 
foo.getAjax(function() { 
    foo.doSomething(); 
}); 
+0

這似乎有點笨重。有沒有那麼標準的解決方案? – miki725

+0

不詳細:'foo.getAjax(foo.doSomething);'這也可能是「笨重」,但它是異步編程的本質。基本的問題是,當AJAX調用返回時你不能保證,所以你需要提供回調或者建立一些事件監聽器系統。回調是迄今爲止比較容易的解決方案。 – Andrew

0

聽起來像你想ajax事件監聽器或回調。做一些搜索,你會發現一些解決方案。他們中的很多人都是基於jQuery的,但如果不適合您的應用程序,那麼無需jQuery就可以做到。

對於jQuery,相關文檔位於http://api.jquery.com/jQuery.ajax/。它不稱之爲事件監聽器,但請參閱關於context的部分以及succes的回調。

另一種可能性是同步執行你的ajax調用,而不是異步執行。 (再次,做一些搜索,你會發現很多東西。)如果你走這條路線,你要小心確保同步調用基本上不會掛你的應用程序等待響應。

0

如果您使用XMLHttpRequest() synchronous您可以按照自己的喜好進行操作。

+0

這樣做會導致頁面,甚至可能用戶的瀏覽器在請求執行時完全凍結。我建議你想避免這樣做。 –

+0

@Tobias我同意 – miki725

相關問題