【问题标题】:Ajax GET method fails to load url, how to retry ajax until success?Ajax GET方法无法加载url,如何重试ajax直到成功?
【发布时间】:2015-03-18 13:43:50
【问题描述】:

我正在创建这个简单的天气应用程序,该应用程序从 openweathermap.org 获取天气数据。从这里我创建这样的 url(你在哪里获取 xml 数据):

http://api.openweathermap.org/data/2.5/forecast/weather?q=Koper,slovenia&mode=xml&units=metric

所以对于我的应用,我使用 jquery 和这段代码从 api 获取数据:

$.ajax({
  type: 'GET',
  dataType: 'xml',
  url: "http://api.openweathermap.org/data...",
}).done(function(data){
  xmlDoc = data;

  //from here I work with xml that I get, and put data into array to display chart
  var time=xmlDoc.getElementsByTagName('time');
  ...
}).fail(function(){
  location.reload(); //this is not a good solution
});

这很好,但我的问题是下一个:有时来自 openweathermap 的服务器不响应我的“url”调用并收到消息错误 404。然后如果你刷新页面(或 url)几个次,然后它的工作原理。对于临时解决方案,我添加了“失败”功能以重新加载页面(location.reload)。但这不是一个好的解决方案,因为当服务器调用失败时,页面会不断重新加载。

知道如何解决这个问题,当服务器无法获取数据时,它会尝试再次重新连接... tnx 寻求帮助

【问题讨论】:

    标签: jquery ajax get


    【解决方案1】:

    你的代码应该是这样的:

    $.ajax({
      type: 'GET',
      dataType: 'xml',
      url: "http://api.openweathermap.org/data...",
      tryCount : 0, // pass this for internal use if fails
      retryLimit : 3 // pass this for internal use if fails
    }).done(function(data){
       ...
       ...
    }).fail(function(xhr, textStatus, errorThrown ){
       if (textStatus == 'timeout') {
                this.tryCount++;
                if (this.tryCount <= this.retryLimit) {
                    //try again
                    $.ajax(this);
                    return;
                }            
                return;
            }
            if (xhr.status == 500) {
                //handle error
            } else {
                //handle error
            }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-12-09
      • 1970-01-01
      • 2021-08-19
      • 2021-04-02
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多