首页 > 解决方案 > 使用jquery从多个url解析json

问题描述

我想从多个 url 解析 json 数据。我尝试使用 for 循环,但它只解析来自 1 个 url 的 json 数据,而我想显示来自所有 url 的数据。

我有一个工作脚本,但它是硬编码的。这是我脚本的一部分。

const apiex1 = 'http://www.ex.com/example1.json';
const apiex2 = 'http://www.ex.com/example2.json';

$.getJSON(apiex1, ex1Weather);
$.getJSON(apiex2, ex2Weather);

function ex1Weather(report) {
    weatherData(report);
    document.querySelector('tbody.ex1').innerHTML = apiWeather;
}
function ex2Weather(report) {
    weatherData(report);
    document.querySelector('tbody.ex2').innerHTML = apiWeather;
}

我有大约 30 个数据/url,使用这个脚本只是压倒性的,因为数据会增加。对此脚本进行更好配置的最佳方法是什么?

标签: javascriptjqueryjsonloops

解决方案


您绝对应该在一组 URL 上使用循环,而不是对每个 URL 进行硬编码。

const apiUrls = ['http://ex.com/example1.json', 'http://ex.com/example2.json'];
apiUrls.forEach((url, index) => {
    $.getJson(url, report => {
        weatherData(report);
        document.querySelector('tbody.ex' + index).innerHTML = apiWeather;
    });
});

推荐阅读