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

发布于 2024-10-16 00:45:50 字数 618 浏览 3 评论 0原文

为什么不返回该函数的responseText?

function LoadBookmarksAsXml()
{
  return $.ajax(
  {
    type: 'GET',
    async: false,
    url:  'http://www.google.com/bookmarks/?output=xml&num=10000'
  }).responseText;
}

(如果我定义一个成功回调函数并将 async 设置为 true,它就会起作用!) 提前致谢!!

编辑:不用担心跨域调用; user603003 说(在对现已删除的答案的评论中)这是在允许跨域请求的 Chrome 扩展中。

如果有人想做同样的事情,解决方案:

return $.ajax(
{
  type: 'GET',
  async: false,
  url:  'http://www.google.com/bookmarks/?output=xml&num=10000',
});

(您将获得一个 XMLHTTPRequest 对象。)

Why don't return that function the 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!!

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.

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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

静待花开 2024-10-23 00:45:50

我没有立即明白为什么它没有返回它,但我仍然使用 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;
}

即使 $.ajax 返回 XMLHttpRequest > 对象(1.4 或更早版本)或 jqXHR 对象(1.5+ 中),我仍然更喜欢使用 success 函数和 error 函数为清晰起见。此外,不同版本的 jQuery 会在出错时为 responseText 提供不同的值(至少在 Chrome 上;1.4.4 返回空字符串,1.5.0 返回 undefined)。


如果有任何方法可以避免它,那就避免它。同步请求完全锁定大多数浏览器的 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);
    }
  });
}

离题:不过,如果请求完全有效,我会感到惊讶,因为从表面上看(除非您在 Google 工作),由于同源政策<,该请求将会失败/a>.绕过 SOP 的各种方法:

I'm not immediately seeing why it's not returning it, but I'd still use a success callback:

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. 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).


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:

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:

九厘米的零° 2024-10-23 00:45:50

$.ajax 从不返回响应文本,它始终返回为进行 Ajax 调用而创建的 XMLHTTPRequest 对象。

我认为您仍然需要定义一个成功回调,例如设置一个局部变量,然后您可以返回该变量。

标准免责声明:同步请求通常是不鼓励的做法,因为它们可能会冻结当前页面。

$.ajax never returns the response text, it always returns the XMLHTTPRequest object created to make the Ajax call.

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.

软糯酥胸 2024-10-23 00:45:50

等待函数的响应不是异步的,ajax 调用完成后会有响应,然后您必须通过定义成功事件的回调来处理响应。

您必须将代码至少分成两部分。第一部分是在 ajax 调用之前,第二部分是在成功之后,并将您想要对请求的数据执行的所有操作都放在成功回调中。异步请求就是这样工作的。

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.

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.

甜妞爱困 2024-10-23 00:45:50

这样做是一个非常糟糕的主意。 JavaScript 将在 HTTP 请求期间阻塞,也就是说,在 ajax 调用返回之前,UI 线程中不会运行任何其他内容。使用回调。

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.

2024-10-23 00:45:50

根据设计,异步请求无法突然传递responseText;-)
您必须设置回调函数并决定如何处理响应文本。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文