【发布时间】: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