3

I have a page where I have implemented a long polling function to check the timestamp of a record, so it will update if the data has been edited.

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

The problem I have is that there is also another action which invokes a JS ajax call, which when called I would like to force the long polling function to stop.
Is there a way to do this?

4

1 回答 1

5

以下 SO 问题可能会提供答案...使用 jQuery 中止 Ajax 请求

将其应用于您的代码片段,您可能会得到类似...

<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>
于 2012-10-22T14:55:00.183 回答