简体   繁体   English

使用 jQuery 和 AJAX 进行长轮询的正确方法是什么

[英]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.所以我偶然发现了使用 socket io 但我还没有足够的时间来学习它。 So I tried doing it with AJAX and jQuery.所以我尝试用 AJAX 和 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.我通常做一个递归函数,允许你等待 ajax 调用之间的间隔而不是固定速率。 //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM. //可选但确实为服务器提供了一些喘息的空间。

  • Use window.setTimeout() with an isActive flag.使用带有 isActive 标志的 window.setTimeout()。 //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.为了彻底,我发现处理 $.ajax() 帖子的错误情况总是一个好主意。 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.这只是我使用您正在使用的确切方法获得的一些东西,似乎 Web Sockets 可能是更好的选择,我将在不久的将来深入研究。

Please refer : Jquery : Ajax : How can I show loading dialog before start and close after close?请参考: Jquery : Ajax: 如何在开始前显示加载对话框并在关闭后关闭?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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