简体   繁体   English

如何使用jQuery执行同步请求?

[英]How can I do a synchronous request with jQuery?

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对象。)

I'm not immediately seeing why it's not returning it, but I'd still use a success callback: 我没有立即看到它为什么不返回它,但我仍然使用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 $.ajax returns an XMLHttpRequest object (in 1.4 or earlier) or a jqXHR object (in 1.5+), I'd still prefer using a success function and an error function for clarity. 尽管$.ajax返回XMLHttpRequest对象(在1.4或更早版本中)或jqXHR对象(在1.5+中),但为了清楚起见,我仍然更喜欢使用success函数和error函数。 Also, different versions of jQuery give you different values for responseText on error (at least on Chrome; 1.4.4 returns an empty string, 1.5.0 returns undefined ). 此外,不同版本的jQuery在出错时为responseText提供不同的值(至少在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). 同步请求完全锁定了大多数浏览器的UI(不仅仅是页面的UI,浏览器管理的每个选项卡中的每个页面)。 Since ajax requests can take a second or two (or five, or ten), this makes for a very unpleasant user experience. 由于ajax请求可能需要一两秒(或五个或十个),这会产生非常不愉快的用户体验。 Nearly all the time, you can avoid it by refactoring your function so it accepts a callback to use to supply the result: 几乎所有时间,您可以通过重构函数来避免它,因此它接受用于提供结果的回调:

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 . 偏离主题 :如果请求完全有效,我会感到惊讶,因为从表面上来看(除非您为Google工作),由于同源策略 ,该请求将失败。 Various ways to get around the SOP: 各种方法来绕过SOP:

$.ajax never 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, eg 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. 标准免责声明:同步请求通常是不鼓励的做法,因为它们可以冻结当前页面。

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. 第一部分是在ajax调用之前,第二部分是在成功之后,并且在成功回调中将您想要做的所有事情与所请求的数据放在一起。 Asyncronous requests work this way. 异步请求以这种方式工作。

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. Javascript将在HTTP请求的持续时间内阻塞,也就是说,在ajax调用返回之前,UI线程中的任何其他内容都不会运行。 Use a callback. 使用回调。

按照设计,异步请求无法提供响应文本;-)您必须设置回调函数并决定如何处理responseText。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM