【发布时间】:2015-09-14 12:35:06
【问题描述】:
很好奇其他人认为构建 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.");
}
});
});
【问题讨论】:
-
您遇到了什么问题?你确定第二个 api 需要 POST 而不是 GET,你没有在 post body 中发送任何数据?
-
很好 - 第二个请求应该是 GET。我这边犯了一个愚蠢的错误,但感谢您看一看。
标签: javascript jquery json ajax