【问题标题】:parsing json from multiple url using jquery使用jquery从多个url解析json
【发布时间】:2019-07-24 17:43:00
【问题描述】:

我想从多个 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 个数据/网址,使用这个脚本只是压倒性的,因为数据会增加。对此脚本进行更好配置的最佳方法是什么?

【问题讨论】:

    标签: javascript jquery json loops


    【解决方案1】:

    您绝对应该对一组 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;
        });
    });
    

    【讨论】:

    • 我尝试了这段代码,但 $.getJSON 不起作用,我尝试记录一些内容但没有返回任何内容。我在 jsfiddle 中试过这个,但它返回错误'$.getJson 不是函数'
    • 您是使用$.getJson 的人。它来自 jQuery,所以如果你要在 jsfiddle 中运行它,你需要包含 jQuery 库。
    • 哦,你可以测试这段代码。我知道它应该有效,但由于某种原因,它不是。
    • 好吧,别管这个问题了。无论如何我都会重建我的代码架构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多