中止与jQuery JSONP Ajax请求 [英] Abort JSONP ajax request with jQuery

查看:182
本文介绍了中止与jQuery JSONP Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是JSONP AJAX调用来加载来自不同领域的一些内容,如果用户产生一个按钮一个鼠标悬停所有这些东西被执行。

I'm using a JSONP ajax call to load some content from a different domain, and all this stuff is executed if the user causes a "mouseover" on a button.

我能捕捉到$。阿贾克斯()调用返回一个XHR对象,并用它在用户每次导致鼠标悬停的时间来终止Ajax请求。但JSONP回调函数依然被调用,这将导致一个错误,我认为这是怎么一回事,因为在xhr.abort()方法并不prevent回调函数被调用。

I can capture the $.ajax() call return as a xhr object, and use it to abort the ajax request each time the user causes a "mouseover". But the JSONP callback function still gets called, and this causes an error, and I think it is beacuse the xhr.abort() method does not prevent the callback function to be called.

我已经试过周围的$。阿贾克斯()与尝试{}赶上(五)称{},但在我打电话的xhr.abort()方法,错误继续。

I've tried surrounding the $.ajax() call with try{}catch(e){}, but after I call the xhr.abort() method, the error continues.

有没有办法来处理异常?

Is there a way to handle that exception?

凸起的例外情况是这样的(根据萤火虫): jQuery16102234208755205157_1308941669256不是一个函数

The raised exception is like this (according to Firebug): jQuery16102234208755205157_1308941669256 is not a function

和异常的内部结构是这样的: jQuery16102234208755205157_1308941669256({...从不同的域我JSON数据....})

And the exception's internal structure is like this: jQuery16102234208755205157_1308941669256({... my json data from a different domain....})

推荐答案

最基本的答案是简单的一个给定的这里 :你真的不能中止() A JSONP调用。所以,真正的问题是,你如何避免这两个多余的回调调用和你看到的错误?

The basic answer is simply the one given here: You can't really abort() a JSONP call. So the real question is, how do you avoid both superfluous callback invocations and the error you're seeing?

您无法使用的try ... catch 周围的回调,因为它是异步的;你必须从jQuery的到底抓它,和jQuery一般不会处理来自回调抛出的异常。 (我讨论这个问题在我的书中,异步的JavaScript 。)你想要做的,而不是什么是使用一个唯一的标识符每个Ajax调用,并调用成功回调时,检查标识符是否相同,当你打了电话了。下面是一个简单的实现:

You can't use try...catch around the callback because it's asynchronous; you'd have to catch it from jQuery's end, and jQuery generally doesn't handle exceptions thrown from callbacks. (I discuss this in my book, Async JavaScript.) What you want to do instead is use a unique identifier for each Ajax call and, when the success callback is invoked, check whether that identifier is the same as it was when you made the call. Here's an easy implementation:

var requestCount = 0;
$.ajax(url, {
  dataType: 'jsonp',
  requestCount: ++requestCount,
  success: function(response, code) {
    if (requestCount !== this.requestCount) return;
    // if we're still here, this is the latest request...
  }
});

在这里,我要带那东西传递给 $的事实。AJAX 连接到这是我们用来作为的对象,这个回调。

Here I'm taking advantage of the fact that anything you pass to $.ajax is attached to the object that's used as this in the callback.

这将会是很好,如果jQuery的做出中止()做,当然这对我们来说。

It'd be nice if jQuery made abort() do this for us, of course.

这篇关于中止与jQuery JSONP Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆