【问题标题】:getJSON error handling - using 2 APIsgetJSON 错误处理 - 使用 2 个 API
【发布时间】:2017-03-03 17:51:18
【问题描述】:

首先它不是另一个跨域错误线程。我正在开发一个简单的 web 应用程序,它使用两个 API(主要和备份)从不同的服务器检索相同的数据。我使用以下模式:

//some functions and variables for DOM handling

$.getJSON(mainUrl, function(results) {

    //code to get and handle the data from main API

}).fail(function() { 

    $.getJSON(backupUrl, function(results) {

        //code to get and handle the data from backup API

    });
});

问题在于主 API 可能会以多种方式失败:

  1. 不响应 - 我的代码按预期正常工作
  2. 响应,但由于 API 服务器的外部问题,返回具有空属性的对象。

第二个选项很棘手,因为它不适合 getJSON .fail 场景。我可以处理的方法是添加一个 if 语句来检查对象属性是否不为空,并从 backupAPI 处理程序中复制代码以检索备份源,所以它看起来像这样:

//some functions and variables for DOM handling

$.getJSON(mainUrl, function(results) {

     if (results.property) {

         //code to get and handle the data from main API

     } else {

         //code to get and handle the data from backup API
     }

}).fail(function() { 

    $.getJSON(backupUrl, function(results) {

        //code to get the data from backup API

    });
});

但是,基本上我在 main.js 文件的两个位置都有相同的代码块,这似乎不是一个好习惯。

你们能帮我妥善解决这个问题,避免在同一地点重复使用相同的代码吗?谢谢。

【问题讨论】:

    标签: javascript json ajax getjson


    【解决方案1】:

    //code to get the data from backup API 放在一个函数中,然后在您放置该代码的任何位置调用该函数怎么样?

    你最终会得到类似的东西

    //some functions and variables for DOM handling
    
    $.getJSON(mainUrl, function(results) {
    
         if (results.property) {
    
             //code to get and handle the data from main API
    
         } else {
    
             getJSONFromBackup();
         }
    
    }).fail(function() { 
    
        getJSONFromBackup();
    
    });
    
    function getJSONFromBackup(){
        $.getJSON(backupUrl, function(results) {
    
            //code to get the data from backup API
    
        });
    }
    

    【讨论】:

    • 好吧,我想这可行。我深入了解 json 错误处理程序,以至于我没有注意到明显的,我的上帝... :) 谢谢
    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 2010-12-16
    • 2011-07-20
    • 2013-10-02
    • 2013-02-10
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多