javascript 如何使用 jQuery 执行同步请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4897193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I do a synchronous request with jQuery?
提问by ComFreek
Why don't return that function the responseText?
为什么不将该函数返回 responseText?
function LoadBookmarksAsXml()
{
return $.ajax(
{
type: 'GET',
async: false,
url: 'http://www.google.com/bookmarks/?output=xml&num=10000'
}).responseText;
}
(It works if I define a success-callback-function and set async to true!) Thanks in advance!!
(如果我定义一个成功回调函数并将 async 设置为 true,它就可以工作!)提前致谢!
Edit: Don't worry about the cross-domain call; user603003 says (in a comment on a now-deleted answer) that this is in a Chrome extension where cross-domain requests are allowed.
编辑:不要担心跨域调用;user603003 说(在对现已删除的答案的评论中)这是在允许跨域请求的 Chrome 扩展程序中。
The solution if someone wants to do the same:
如果有人想做同样的事情,解决方案是:
return $.ajax(
{
type: 'GET',
async: false,
url: 'http://www.google.com/bookmarks/?output=xml&num=10000',
});
(You will get a XMLHTTPRequest object.)
(您将获得一个 XMLHTTPRequest 对象。)
回答by T.J. Crowder
I'm not immediately seeing why it's not returning it, but I'd still use a successcallback:
我没有立即明白为什么它不返回它,但我仍然会使用success回调:
function LoadBookmarksAsXml()
{
var result;
$.ajax(
{
type: 'GET',
async: false,
url: 'http://www.google.com/bookmarks/?output=xml&num=10000',
success: function(data) {
result = data;
}
});
return result;
}
Even though $.ajaxreturns an XMLHttpRequestobject (in 1.4 or earlier) or a jqXHRobject (in 1.5+), I'd still prefer using a successfunction and an errorfunction for clarity. Also, different versions of jQuery give you different values for responseTexton error (at least on Chrome; 1.4.4 returns an empty string, 1.5.0 returns undefined).
即使$.ajax返回一个XMLHttpRequest对象(在 1.4 或更早版本中)或一个jqXHR对象(在 1.5+ 中),为了清晰起见,我仍然更喜欢使用一个success函数和一个error函数。此外,不同版本的 jQuery 为您提供不同的responseTexton error值(至少在 Chrome 上;1.4.4 返回空字符串,1.5.0 返回undefined)。
If there's any way you can avoid it, avoid it. Synchronous requests completely lock up the UI of most browsers (not just your page's UI, every page in every tab that browser is managing). Since ajax requests can take a second or two (or five, or ten), this makes for a very unpleasant user experience. Nearly all the time, you can avoid it by refactoring your function so it accepts a callback to use to supply the result:
如果有任何方法可以避免它,请避免它。同步请求完全锁定了大多数浏览器的 UI(不仅仅是页面的 UI,浏览器管理的每个选项卡中的每个页面)。由于 ajax 请求可能需要一两秒钟(或五秒钟或十秒钟),这会导致非常不愉快的用户体验。几乎所有时间,您都可以通过重构您的函数来避免它,以便它接受用于提供结果的回调:
function LoadBookmarksAsXml(callback)
{
$.ajax(
{
type: 'GET',
url: 'http://www.google.com/bookmarks/?output=xml&num=10000',
success: function(data) {
callback(data);
},
error: function() {
callback(null);
}
});
}
Off-topic: I'll be surprised if the request works at all, though, because on the face of it (unless you work for Google), that request will fail because of the Same Origin Policy. Various ways to get around the SOP:
题外话:不过,如果该请求有效,我会感到惊讶,因为从表面上看(除非您为 Google 工作),该请求将因Same Origin Policy 而失败。绕过 SOP 的各种方法:
- JSONP
- CORS(but it requires browser support and that www.google.com allow the request from your origin)
- Using YQL as a proxy
- JSONP
- CORS(但它需要浏览器支持并且 www.google.com 允许来自您的来源的请求)
- 使用 YQL 作为代理
回答by Pekka
$.ajaxnever returns the response text, it always returns the XMLHTTPRequest object created to make the Ajax call.
$.ajax从不返回响应文本,它总是返回为进行 Ajax 调用而创建的 XMLHTTPRequest 对象。
You'll still need to define a success callback I think, e.g. one setting a local variable which you can then return.
我认为您仍然需要定义一个成功回调,例如设置一个局部变量,然后您可以返回该变量。
Standard disclaimer: Synchronous requests are a usually discouraged practice because they can freeze the current page.
标准免责声明:同步请求通常是不鼓励的做法,因为它们可以冻结当前页面。
回答by aorcsik
Waiting for the response of a function is not asyncronous, the ajax call will have a response when it is done, you have to take care of the response then, by defining callbacks for the successful event.
等待函数的响应不是异步的,ajax 调用完成后会有响应,然后你必须通过定义成功事件的回调来处理响应。
You have ti break up your code to at least two parts. First part is before the ajax call, second part is after the success, and put everything you want to do with the requested data in the success callback. Asyncronous requests work this way.
您必须将代码分解为至少两部分。第一部分是ajax调用之前,第二部分是成功之后,把你想要对请求的数据做的所有事情都放在成功回调中。异步请求以这种方式工作。
回答by Zachary K
Doing that is a really bad idea. Javascript will block for the duration of the HTTP request, which is to say nothing else in the UI thread will run until the ajax call returns. Use a callback.
这样做是一个非常糟糕的主意。Javascript 将在 HTTP 请求期间阻塞,也就是说 UI 线程中的任何其他内容都不会运行,直到 ajax 调用返回。使用回调。
回答by Capsule
By design, asynchronous requests can't deliver a responseText out of the blue ;-) You HAVE to set a callback function and decide how you will handle the responseText.
按照设计,异步请求不能突然传递 responseText ;-) 您必须设置回调函数并决定如何处理 responseText。

