关于jquery:如何对服务器进行JavaScript同步调用?

How can I make a JavaScript synchronous call to the server?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request?

我有一个返回初始化数据的方法。它首先检查会话存储。如果在那里找不到数据,它会调用服务器来获取数据。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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方法的返回语句之前执行?


使用async: false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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"));
}