时间 ajax 请求



有没有办法确定jquery ajax请求已经进行了多长时间? 有时搜索时间太长,如果搜索需要 5 秒,最好添加一个 jquery abort() 按钮。我能做到什么!

在 ajax 请求的另一端是一个发出 postgresql 请求的 php 文件。

非常感谢您的任何想法!

查看超时选项 (http://api.jquery.com/jQuery.ajax/)。 您可以在特定调用上设置它,也可以使用 $.ajaxSetup() 全局设置它。

要在 5 秒后显示中止按钮,请在调用 send 后添加一个 setTimeout 函数。AJAX 命令完成后,可以添加代码以清除超时并删除中止按钮(如果存在)。

var timeOutID = 0;
$.ajax({
  url: 'ajax/test.html',
  success: function(data) {     
    clearTimeOut(timeOutID);
    // Remove the abort button if it exists.
  }
});
timeOutID = setTimeout(function() {
                 // Add the abort button here.
               }, 5000);   

这样,如果 AJAX 返回速度足够快,中止按钮将永远不会出现。

通常,我会在发送请求后设置超时,该超时将在 10 秒左右后触发,然后回退到其他内容以确保它仍然发生(例如,表单提交)。

所以将变量设置为 false,var failed = false;并执行请求在请求启动的同时,设置超时:

setTimeout(function() {
    failed = true;
    $("#form").submit();
    return false;
}, 10000);

在 ajax 调用的返回函数中,检查失败的变量是否已设置为 true,如果有,则不要实际执行它最初尝试的任何事情,否则它可能会搞砸某些事情,或者在发生其他事情时让用户感到困惑(因为这些事情通常发生在较慢的互联网连接上, 如果在加载新页面时出现下一步,他们可能会尝试交互,然后页面将更改)。

$.post("ajaxcall.php", {'etc': "etc"},
    function(returned) {
        if (failed != true) {
            //do whatever with returned variable
        }
});
var timer = 0,
    XHR = $.ajax({
             url: 'ajax/mypage.html',
             beforeSend: function() {
                 timer=setTimeout(showAbort, 5000);
             }
          });
function showAbort() {
    $('<input type="button" value="Abort" id="abort_button"/>').appendTo('#some_parent');
    $('#abort_button').on('click', function() {
         XHR.abort(); //abort the Ajax call
    });
}
XHR.always(function() {  //fires on both fail and done
    clearTimeout(timer);
    if ($('#abort_button').length) {
       $('#abort_button').remove(); //remove button if exists
    }
});

最新更新