【问题标题】:Stop Long Polling Function in JS停止 JS 中的长轮询函数
【发布时间】:2012-10-12 02:39:23
【问题描述】:

我有一个页面,我实现了一个长轮询功能来检查记录的时间戳,因此如果数据已被编辑,它将更新。

<script type="text/javascript">
var poll_url = 'http://mysite.com/poll/;
var my_ts = <?php $_SESSION['template_timestamp']; ?>;
(function poll(){
    $.ajax({ 
        url: poll_url,
        type: 'post',
        success: function(data){
            if ((data.ts > 0) {
                // check if expired
                if (data.ts > my_ts) {
                    // it has expired, so reload the page
                    $("#dialog-message").html('Record has been edited.');
                    // show popup
                    $("#dialog-message").dialog({
                        modal: true,
                        buttons: {
                            Reload: function() {
                                $(this).dialog("close");
                                $('#pleaseWait').show();
                                window.location.href = '/records/overview';
                            }
                        }
                    });
                }
            } else {
                // is still null
                console.log('error');
            }
        }, 
        dataType: "json", 
        complete: poll, timeout: 30000 
    });
})();
</script>

我遇到的问题是还有另一个调用 JS ajax 调用的操作,当调用它时我想强制长轮询函数停止。
有没有办法做到这一点?

【问题讨论】:

  • 以下 SO 问题可能会提供答案...stackoverflow.com/questions/446594/…
  • @StuartWakefield ;谢谢你。没找到那个sn-p。如果您将该评论作为答案发布,我会接受。

标签: javascript ajax jquery long-polling


【解决方案1】:

以下 SO 问题可能会提供答案...Abort Ajax requests using jQuery

将其应用于您的代码 sn-p,您可能会得到类似...

<script type="text/javascript">
var poll_url = 'http://mysite.com/poll/';
var my_ts = <?php $_SESSION['template_timestamp']; ?>;
var poll_xhr;

(function poll(){
    poll_xhr = $.ajax({ 
        url: poll_url,
        type: 'post',
        success: function(data){
            // Code removed
        }, 
        dataType: "json", 
        complete: poll, 
        timeout: 30000 
    });
})();

// To kill the AJAX request, put this where it makes sense
poll_xhr.abort();
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    相关资源
    最近更新 更多