5

重複の可能性:
jQuery で非同期ではなく同期の AJAX 要求を実行するにはどうすればよいですか?

初期化データを返すメソッドがあります。最初に 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 ステートメントの前に成功関数を実行する必要があるように、サーバー呼び出しを同期させるにはどうすればよいですか?

4

1 に答える 1

8

使用する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"));
}
于 2013-01-08T15:18:19.343 に答える