如何杀死旧的 jsonp 请求?
我有一个使用 getJSON 的跨域长轮询请求,其回调如下所示:
$.getJSON("http://long-polling.com/some.fcgi?jsoncallback=?"
function(data){
if(data.items[0].rval == 1) {
// update data in page
}
});
问题是对长轮询服务的请求可能需要一段时间才能返回,同时可能会发出另一个 getJSON 请求并更新该页面,即使它是一个陈旧的响应。
要求1: h**p://long-polling.com/some.fcgi 位于 上午 10:00
要求2: h**p://long-polling.com/some.fcgi?在 上午 10:01
Req1 返回并更新数据 该页面上午 10:02
我想要一种方法,如果 Req2 已经完成,则使 Req1 的返回无效。
谢谢!
I have a cross-domain long polling request using getJSON with a callback that looks something like this:
$.getJSON("http://long-polling.com/some.fcgi?jsoncallback=?"
function(data){
if(data.items[0].rval == 1) {
// update data in page
}
});
The problem is the request to the long-polling service might take a while to return, and another getJSON request might be made in the meantime and update the page even though it is a stale response.
Req1:
h**p://long-polling.com/some.fcgi at
10:00 AMReq2:
h**p://long-polling.com/some.fcgi? at
10:01 AMReq1 returns and updates the data on
the page 10:02 AM
I want a way to invalidate the return from Req1 if Req2 has already been made.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这不起作用,因为 getJSON 使用 JSONP 方法,该方法实际上是通过动态插入浏览器执行的脚本标签来工作的。我认为没有任何方法可以阻止浏览器执行脚本......有吗?
I don't think that works as the getJSON uses JSONP method which actually works by dynamically inserting a script tag which your browser executes. I don't think there is any way to stop the browser from executing the script...is there?
当您发出 ajax 请求时,它会返回 XMLHttpRequest 对象。如果您想
中止
调用,您可以调用它的.abort()
方法。When you make the ajax request it returns the XMLHttpRequest object. If you want to
abort
the call you can call the.abort()
method on it.正如@NewToDB提到的,您无法取消jsonp请求(例如告诉浏览器停止尝试加载标签的src),但您可以实现一种机制,有效地忽略旧调用的返回数据。定义一个全局变量,每次进行 jsonp 调用时该变量都会递增,并将该变量的值作为参数传递给服务器。您还需要将计数器从服务器传回(我假设您也拥有服务器代码)。如果计数器的当前值不等于返回的计数器值,那么您就知道已经进行了另一个服务器调用,因此您可以忽略返回的数据。
...
As @NewToDB mentioned, you cannot cancel the jsonp request (e.g. tell the browser to stop trying to load the src of a tag), but you could implement a mechanism that effectively ignores the returned data of the old call. Define a global variable that is incremented each time you are going to make the jsonp call and pass the value of that variable to the server as a parameter. You also need to pass it the counter back from the server (I'm assuming you also own the server code). If the current value of your counter is not equal to the returned counter value then you know that another server call has already been made, so you can ignore the returned data.
...
我使用全局变量来完成此类任务。这不是一个很好的方法,但却是最简单的一种。
I use global variable for such task. This is not a pretty good way, but the simplest one.