我正在尝试使用以下 API https://postcodes.io/并使用 AJAX 执行批量查找。
我可以使用文档中提供的语法进行单个邮政编码查找,如下所示:
$.ajax({
type: "POST",
url: 'https://api.postcodes.io/postcodes/BS16AA',
success: function (response) {
console.log(response);
},
error: function (xhr, ajaxOptions, thrownError) {
var msg = '';
if (xhr.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (xhr.status == 404) {
msg = 'Requested page not found. [404]';
} else if (xhr.status == 500) {
msg = 'Internal Server Error [500].';
} else if (thrownError === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (thrownError === 'timeout') {
msg = 'Time out error.';
} else if (thrownError === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + xhr.responseText;
}
}
});
然而,“批量查找”的示例不太有用(看起来它想要一个在名为
"postcodes: [myArrayHere]"
的属性下具有数组的对象)我还没有设法找到一个工作示例或自己创建一个。使用上面的示例代码和批量查找的语法,我只想执行几次 ajax 调用来查找大约 200 个邮政编码(该站点说一次限制为 100 个,因此我可以将它们分成几个数组)。在一个循环中查找 200 个邮政编码所花费的时间对于我的项目来说并不真正可行。
最佳答案
你需要像下面一样使用它
$.ajax({
type: "POST",
url: 'https://api.postcodes.io/postcodes/',
data: { postcodes: ["code1", "code2"] }
success: function (response) {
console.log(response);
},
error: function (xhr, ajaxOptions, thrownError) {
var msg = '';
if (xhr.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (xhr.status == 404) {
msg = 'Requested page not found. [404]';
} else if (xhr.status == 500) {
msg = 'Internal Server Error [500].';
} else if (thrownError === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (thrownError === 'timeout') {
msg = 'Time out error.';
} else if (thrownError === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + xhr.responseText;
}
}
});
查看他们拥有的测试用例,其中显示了预期的数据
https://github.com/ideal-postcodes/postcodes.io/blob/373fda002692542f21330088154d3d4965a1cd65/tests/filter.integration.js#L33
关于ajax - Postcodes.io 批量查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50447385/