【问题标题】:Architecture for Multiple API Calls Using jQuery and Javascript使用 jQuery 和 Javascript 进行多个 API 调用的架构
【发布时间】:2015-09-14 12:35:06
【问题描述】:

很好奇其他人认为构建 API 调用的最佳方式,该调用依赖于 jQuery 中另一个 API 调用的响应。

步骤:

  1. 对端点进行 API JSONP 调用,接收响应
  2. 如果我们从第一次调用中获得 200 成功响应,我们将触发另一个 API 调用(这次是 JSON)。
  3. 将结果输出到浏览器中。

这就是我用一些粗略的错误处理来构造它的方式:

$(document).ready(function() {
  $.ajax({
     url: "http://example.com/json",
     type: 'POST',
     dataType: 'jsonp',
     timeout: 3000,
     success: function(data) {

       // Variables created from response
       var userLocation = data.loc;
       var userRegion = data.city;

       // Using variables for another call
       $.ajax({
         url: "http://example2.com/json?Location=" + userLocation + "&City=" + userRegion,
         type: 'POST',
         dataType: 'json',
         timeout: 3000,
         success: function(Response) {
          $(.target-div).html(Response.payload);
         },
         error: {
          alert("Your second API call blew it.");
         }
       });

     },
     error: function () {
       alert("Your first API call blew it.");
     }
  });
});

【问题讨论】:

  • 您遇到了什么问题?你确定第二个 api 需要 POST 而不是 GET,你没有在 post body 中发送任何数据?
  • 很好 - 第二个请求应该是 GET。我这边犯了一个愚蠢的错误,但感谢您看一看。

标签: javascript jquery json ajax


【解决方案1】:

在架构方面,您可以考虑使用 Promise 模式将每个步骤解耦为一个函数,每个函数只关心自己的任务(不要引用流程中的另一个步骤)。当您需要重用这些步骤时,这提供了更大的灵活性。这些单独的步骤可以在以后链接在一起形成一个完整的流程。

https://www.promisejs.org/patterns/

http://api.jquery.com/jquery.ajax/

http://api.jquery.com/category/deferred-object/

  function displayPayload(response) {
    $(".target-div").html(response.payload);
  }

  function jsonpCall() {
    return $.ajax({
      url: "http://example.com/json",
      type: 'GET',
      dataType: 'jsonp',
      timeout: 3000
    });
  }

  function jsonCall(data) {
    // Variables created from response
    var userLocation = data.loc;
    var userRegion = data.city;

    // Using variables for another call
    return $.ajax({
      url: "http://example2.com/json?Location=" + userLocation + "&City=" + userRegion,
      type: 'GET',
      dataType: 'json',
      timeout: 3000
    });
  }

  $(document).ready(function() {
    jsonpCall()
      .done(function(data) {
        jsonCall(data)
          .done(function(response) {
            displayPayload(response);
          }).fail(function() {
            alert("Your second API call blew it.");
          });
      }).fail(function() {
        alert("Your first API call blew it.");
      });
  });

【讨论】:

  • 我试过了,这正是我想要的:一种将代码抽象为更模块化的方法。谢谢JM。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2016-01-26
  • 2022-01-05
  • 1970-01-01
相关资源
最近更新 更多