我是新手,正在学习 JSON
,但在显示某些 API
结果时遇到问题:
$.getJSON(url, function (data) {
enText = data.data.count;
arText = data.data.matches.text;
document.getElementById('verseText').innerHTML = 'Matches: '+enText+'';
document.getElementById('demo').innerHTML = arText;
})
enText
工作正常,但如何使用 JSON
(上面)将所有匹配的文本列出到 HTML
列表中
假设这是端点:http://api.alquran.cloud/v1/search/abraham/all/en
最佳答案
在您的 API 响应中,matches
是一个对象数组。因此,您需要迭代循环来访问 text
值
$.getJSON("http://api.alquran.cloud/v1/search/abraham/all/en", function (data) {
enText = data.data.count;
arText = data.data.matches;
var li= '';
for (const x of arText) {
li+='<li>'+x.text+' <span class="surah">'+x.surah.name+'</span></li>';
}
document.getElementById('verseText').innerHTML = 'Matches: ' + enText + '';
document.getElementById('demo').innerHTML = li;
})
否则,如果您想要单个数据,请使用索引值获取它。就像下面的代码
arText = data.data.matches[0].text;
document.getElementById('demo').innerHTML = arText;
关于javascript - 如何从 JavaScript 中的 JSON 有效负载获取所有匹配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64224852/