使用jQuery和AJAX进行长轮询的正确方法是什么 [英] What is the proper way of doing long polling using jQuery and AJAX
问题描述
我有一个涉及实时通知的项目。所以我偶然发现使用socket io但我还没有足够的时间来学习它。所以我尝试用AJAX和jQuery来做。下面是我的代码结构,我想知道这是否会没有缺点?
I have a project which involves live notification. So I stumbled upon using socket io but I didn't have enough time to learn it yet. So I tried doing it with AJAX and jQuery. Below is my code structure and I was wondering if this is gonna work with no drawbacks?
setInterval(function(){
if( !element.hasClass('processing') ){
element.addClass('processing');
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {},
success: function( response ){
/* Success! */
element.removeClass('processing');
}
});
}
}, 2500);
推荐答案
一些额外信息
您描述的方式将起作用。从经验中我想指出一些事情。
Some Extra Info
The way you described will work. From Experience I would just like to point out some things.
-
我通常做一个递归函数,让你等待你的间隔在ajax呼叫之间而不是固定费率。 //可选但是给服务器一些呼吸室。
I usually do a recursive function, allows you to wait your interval between ajax calls and not a fixed rate. //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM.
使用带有isActive标志的window.setTimeout()。 //允许你停止投票,无论原因是什么,并且因为需要再次启动功能
Use window.setTimeout() with an isActive flag. //ALLOWS YOU TO STOP POLLING FOR WHATEVER REASON, AND BECAUSE FUNCTION IS RECURSIVE START UP AGAIN IF NEED BE
为了彻底清醒,我发现它是总是一个好主意来处理$ .ajax()帖子的错误情况。您可以显示一些消息,告诉用户他不再连接到互联网等。
For Sake of being thorough, I found it is always a good idea to handle the error case of the $.ajax() post. You could perhaps display some message telling the user he is no longer connected to the internet etc.
一些示例代码:
var isActive = true;
$().ready(function () {
//EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
//IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
pollServer();
});
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "...",
type: "POST",
success: function (result) {
//SUCCESS LOGIC
pollServer();
},
error: function () {
//ERROR HANDLING
pollServer();
}});
}, 2500);
}
}
注意
这只是我使用您使用的确切方法获取的一些内容,似乎Web套接字可能是更好的选择,我将在不久的将来深入探讨。
NOTE
This is just some things I picked up using the exact method you are using, It seems that Web Sockets could be the better option and I will be diving into that in the near future.
这篇关于使用jQuery和AJAX进行长轮询的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!