Javascript 检测ajax成功函数何时超过5秒并重定向

Javascript 检测ajax成功函数何时超过5秒并重定向,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,您好,我有一个脚本,它可以在不加载页面的情况下从一个页面移动到一个href 它工作得很好,但是如果Ajax需要5秒以上的响应时间,我想重定向到请求的页面,这通常是由于internet连接速度较慢造成的。 在这种情况下:停止脚本并正常加载页面 首先,href: <a href="new.php" rel="tab">new</a> <a href="new1.php" rel="tab">New 1</a> 以下是脚本: <script&

您好,我有一个脚本,它可以在不加载页面的情况下从一个页面移动到一个href

它工作得很好,但是如果Ajax需要5秒以上的响应时间,我想重定向到请求的页面,这通常是由于internet连接速度较慢造成的。 在这种情况下:停止脚本并正常加载页面

首先,href:

<a href="new.php" rel="tab">new</a>
<a href="new1.php" rel="tab">New 1</a>  
以下是脚本:

<script>
$(function(){ 
  $("a[rel='tab']").click(function(e){
    pageurl = $(this).attr('href'); //get the href clicked
    $.ajax({url:pageurl+'?rel=tab',
      success: function(data){
        $('#mole').html(data); 
      }
    }); 
    if(pageurl!=window.location){
      window.history.pushState({
        path:pageurl
      },'',pageurl);    
    }
    return false;  
  });
});

$(window).bind('popstate', function(){
  $.ajax({
    url:location.pathname+'?rel=tab',
    success: function(data){
      // here how do I detect if the success takes longer than 5 seconds
      // stop the script and load the page normally which is the URL parameter in ajax
      $('#mole').html(data); 
    }
  }); 
}); 
</script>

首先,我们需要向ajax处理程序添加一个超时,这样它将在5秒后取消请求。在这里,我们使用5000毫秒。然后,根据,head to error,您可以看到第二个参数是textStatus。如果是超时,则等于超时。这可能是你需要做的最简单的方法。根据您的功能需要更新错误处理程序

$(window).bind('popstate', function() {
    var url = location.pathname + '?rel=tab';
    $.ajax({
        timeout: 5000,
        url: url,
        success: function(data) {
            $('#mole').html(data);
        },
        error: function(jqXHR, textStatus) {
            if (textStatus === 'timeout') {
                // we know the ajax failed due to a timeout,
                // do what you need here, below is an example.
                window.location = url;
            }
        }
    });
});