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 方法的返回语句之前执行?

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 回答