想知道其他人认为什么是架构师进行 API 调用的最佳方式,该 API 调用依赖于 jQuery 中另一个 API 调用的响应。
步骤:
- 对端点进行 API JSONP 调用,接收响应
- 如果我们从第一次调用中获得 200 成功响应,我们将触发另一个 API 调用(这次是 JSON)。
- 将结果输出到浏览器。
这就是我用一些粗略的错误处理来构建它的方式:
$(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/