2017-03-29 21 views
0

你好,我有這個腳本,從一頁通過href沒有頁面加載移動。檢測Ajax成功函數的時間超過5秒,並重定向

它可以很好地工作,但我想重定向到請求的頁面,如果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> 

回答

1

首先,我們需要添加超時ajax的處理程序,以便它會在5秒後取消該請求(在這裏我們使用5000毫秒)。然後,根據docs,前往error,您可以看到第二個參數爲textStatus。如果是超時,這將等於"timeout"。這可能是你需要做的最簡單的途徑。根據您的功能需要更新錯誤處理程序。

$(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; 
      } 
     } 
    }); 
});