如何对服务器进行JavaScript同步调用?

时间:2013-01-08 15:13:51

标签: javascript jquery ajax sync

  

可能重复:
  How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request?

我有一个返回初始化数据的方法。它首先检查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语句之前执行?

1 个答案:

答案 0 :(得分: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"));
}