2013-01-08 51 views
1

可能重複:
How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request?如何使JavaScript同步調用服務器?

我有一個返回值初始化數據的方法。它首先檢查sessionStorage。如果它沒有在那裏找到數據,它會調用服務器來獲取數據。這裏是代碼:

function getInitializationData() { 

// Check local storage (cache) prior to making a server call. 
// Assume HTML 5 browser because this is an Intranet application. 
if (!sessionStorage.getItem("initialData")) { 

    // The browser doesn't have the initialization data, 
    // so the client will call the server to get the data. 
    // Note: the initialization data is complex but 
    // HTML 5 storage only stores strings. Thus, the 
    // code has to convert into a string prior to storage. 
    $.ajax({ 
     url: "../initialization.x", 
     type: "POST", 
     dataType: "json", 
     timeout: 10000, 
     error: handleError, 
     success: function(data) { sessionStorage.setItem("initialData", JSON.stringify(data)); } 
    }); 
} 

// convert the string back to a complex object 
return JSON.parse(sessionStorage.getItem("initialData")); 
} 

問題是,成功函數幾乎總是在方法返回後執行。我怎樣才能使服務器調用同步,使得成功函數必須在getInitializationData方法的return語句之前執行?

+12

這個問題得到每天問...你可以把它同步,但它通常是一個壞主意。讓'getInitializationData'接受回調或查看延期對象(http://api.jquery.com/category/deferred-object/)。現在要寫一個規範的問題/答案,因爲在某個時候它已經足夠了...... –

+1

你有沒有讀過jQuery API? 'async:false' –

+1

http://api.jquery.com/jQuery.ajax/ - 谷歌搜索的第一個結果「jquery ajax synchronized」 – iamnotmaynard

回答

6

使用async: false

function getInitializationData() { 

// Check local storage (cache) prior to making a server call. 
// Assume HTML 5 browser because this is an Intranet application. 
if (!sessionStorage.getItem("initialData")) { 

    // The browser doesn't have the initialization data, 
    // so the client will call the server to get the data. 
    // Note: the initialization data is complex but 
    // HTML 5 storage only stores strings. Thus, the 
    // code has to convert into a string prior to storage. 
    $.ajax({ 
     url: "../initialization.x", 
     type: "POST", 
     dataType: "json", 
     timeout: 10000, 
     async: false, 
     error: handleError, 
     success: function(data) { sessionStorage.setItem("initialData", JSON.stringify(data)); } 
    }); 
} 

// convert the string back to a complex object 
return JSON.parse(sessionStorage.getItem("initialData")); 
} 
+1

@骯髒的流噢來吧...不是每個人都知道的。夥計想要總和點數! – mraaroncruz

+0

@髒流:每天都會關閉大量問題,每天都會問這些基本問題。這並不意味着當你遇到這樣一個問題時你不會回答。 – gopi1410