简体   繁体   中英

What is the proper way of doing long polling using jQuery and 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.

Please refer : Jquery : Ajax : How can I show loading dialog before start and close after close?

I hope this could help you

$("div.add_post a").click(function(){

  var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
            dlg.dialog("show");
  $.ajax({
        url : "/add.php",
        complete : function (){
            dlg.dialog("hide");
        }
     });
 return false;
});


//--Loading dialog

function loadingDialog(dOpts, text = "пожалуйста подождите, идет загрузка...")
{
    var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt='загрузка'/> "+text+"<div>").dialog(dOpts);
    $(".ui-dialog-titlebar").hide();

    return dialog;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM