【问题标题】:How can I make a JavaScript synchronous call to the server? [duplicate]如何对服务器进行 JavaScript 同步调用? [复制]
【发布时间】:2012-12-22 11:43:41
【问题描述】:

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

【问题讨论】:

  • 这个问题每天都会被问到......你可以让它同步,但这通常是个坏主意。让getInitializationData 接受回调或查看延迟对象 (api.jquery.com/category/deferred-object)。现在要写一个规范的问题/答案,因为在某些时候它就足够了......
  • 你读过 jQuery API 吗? async:false 呢?
  • api.jquery.com/jQuery.ajax -- 谷歌搜索“jquery ajax synchronized”的第一个结果
  • 具有讽刺意味的是,OP 在编写初始问题时必须绕过的问题数量,并且公然无视右侧的列表。 ;p
  • 您可以在$.ajax 调用中将async: false 添加到您的选项中,这样就可以解决问题。然而,该属性已被弃用,并且可能在未来的版本中不受支持。

标签: javascript jquery ajax sync


【解决方案1】:

使用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"));
}

【讨论】:

  • @Dirty-flow 哦,拜托……不是每个人都知道。老兄要总分!
  • @Dirty-flow:每天都有大量问题被关闭,每天都会问这些类型的基本问题。这并不意味着当你遇到这样一个问题时你不回答。
猜你喜欢
  • 2017-10-03
  • 2010-09-22
  • 2016-04-19
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 2012-06-17
  • 1970-01-01
相关资源
最近更新 更多