ajax长轮询java代码,使用jQuery和AJAX进行长轮询的正确方法是什么

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.

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.

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

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.

Some Sample Code:

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

}

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值