javascript - 使用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,使用这个脚本只是压倒性的,因为数据会增加。对此脚本进行更好配置的最佳方法是什么?
解决方案
您绝对应该在一组 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;
});
});
推荐阅读
- javascript - 如何在 reactjs 中的 Whatsapp 上共享带有文本的图像?
- windows - 卷曲 + 调用 RestMethod
- javascript - 无法正确找到数据
- python - 有没有办法使用 Pandas Dataframes 在 Excel 中设置敏感度标签?
- python - Docker 使用 AWS 中的 Celery 和 Redis 部署烧瓶应用程序,AWS RDS 中的 DB
- eslint - 如何修复/禁用看似错误的“模块中未找到命名导出”错误?
- node.js - 生产中的 Node.js 应用程序部署?
- javascript - jQuery DataTables:以原始数据源顺序显示行,同时保持排序功能可用
- curl - cURL 用于在站点需要登录时下载文件
- bash - Bash 脚本无法找到 .JAR 文件