【问题标题】:How to correctly handle ajax timeouts如何正确处理ajax超时
【发布时间】:2018-05-27 00:57:12
【问题描述】:

例如,用户想登录,连接慢或者请求卡在某个网络中,然后用户等待,但有时重发请求比等待更好。

问题:

  • 理想的等待时间是多少? (没有上传文件,只是 简单登录)我已经放了 15 秒,但可能太多了。
  • 最好的解决方案是什么?

1) 让用户等待,直到他决定再次点击登录

2) 设置 ajax 超时

$.ajax({

url: '{{ url('/login') }}',
data: data,
method: 'POST',
timeout: 15000, 

并向他们显示错误

error: function(data, status, error){

if(status==="timeout") {
var errorString = 'Please retry. Ref Timeout';                      
}

3) 自动重试 (code)

$.ajax({
url : 'someurl',
type : 'POST',
data :  ....,   
tryCount : 0,
retryLimit : 3,
...
error: function(data, status, error){
    if (status == 'timeout') {
       this.tryCount++;
       if (this.tryCount <= this.retryLimit) {
       //try again
           $.ajax(this);
           return;
       }            
       return;
    }

4) 在 ajax 上使用包装函数

setTimeout(function(){
    $.ajax({...})
}, 15000);

5)Some other options

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    我会亲自做一个混合,也就是说,尝试 2 次和秋天,你可以使用这个代码:

    $.ajax({
    
        url: '{{ url('/login') }}',
        data: data,
        method: 'POST',
        timeout: 10000, // sets timeout to 5000 = 5 seconds
        retryCount: 0, // start retry count
        retryLimit: 1, //will let you retry a determined number of times
    
    error: function(data, status, error){       
    
    if(status==="timeout") {
        this.retryCount++;
        if (this.retryCount <= this.retryLimit) { //&& Date.now() - this.created <  this.retryTimeout
            console.log("Retrying");
            $.ajax(this);
            return;
    }
    else{
        var errorString = 'Timeout';                        
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用像 https://github.com/inmar/patience_js 这样的库来定义重试策略并保持代码更简洁。

      或者更好的是看看RxJS

      您可以使用此处建议的方法:RxJS retry operator with ajax call

      const doLogin = () => {
          console.log('calling');
          return $.ajax('...')
      };
      
      const stream = Rx.Observable.fromPromise(doLogin).retry(3);
      
      stream.subscribe(log);
      

      【讨论】:

        【解决方案3】:

        默认的服务器超时时间是 30 秒,所以在 Ajax 中它是正确的超时时间。

        不要用重新登录来轰炸服务器(如果它太忙,你会让它变得更糟)。

        在请求待处理时,不允许用户再次单击登录按钮。


        IMO 应该有没有超时的 ajax,如果出错,您应该告诉用户稍后再试。

        $.ajax({
            error: function (response) {
                console.error(response); // Show error response to dev
        
                alert('Something went wrong. Please try again later or contact administrator admin@email.com'); // Use pretty modal instead
            }
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-02
          • 1970-01-01
          • 2023-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多