javascript - 使用 jQuery 和 Javascript 的多个 API 调用架构

标签 javascript jquery json ajax

想知道其他人认为什么是架构师进行 API 调用的最佳方式,该 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.");
     }
  });
});

最佳答案

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

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.");
      });
  });

关于javascript - 使用 jQuery 和 Javascript 的多个 API 调用架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32564971/

相关文章:

javascript - jqGrid onSelectRow 不工作

javascript - 无法在服务器日志中显示request.body?

jquery - 如何使用 Spring Security 和 jQuery 处理过期 session ?

javascript - 模态弹出控件不起作用

javascript - 如何使用正则表达式从文件中加载 jquery 中的 json?

javascript - 与浏览器中的全局范围相比,node.js 中的全局范围有何不同(带有具体示例)?

javascript - 绑定(bind)到内部有 $http 的函数时遇到无限摘要循环

ASP.NET AJAX 和 JQuery 问题

php - 自动加载 bitbucket 存储库 + composer.json

java - 如何在kotlin中获取多维原始数组类?