ajax - Postcodes.io 批量查找

标签 ajax

我正在尝试使用以下 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/

相关文章:

java - 如何将ajax中的值设置到jsp中的表中

javascript - 为什么我不能让 jQuery 的 live() 或 load() 工作?

javascript - 我是否有可能阻止黑客使用 Web 控制台使用 JavaScript 重复调用 upvote (AJAX) 函数?

加载图像时 jQuery 403 禁止

jquery - Ajax jquery过滤部分html

php - 如何使用 $_POST 保存 contentEditable ="true"的 Div?

php - 在sql select和update语句中使用从下拉列表获取的php动态变量

javascript - Rails View 中的 Json 对象

javascript - 使用javascript更改部分链接

javascript - jQuery 的 .on 函数似乎不喜欢 'load' 事件