我试图从此 JSON 文件中仅获取所选项目:
{
"faqs": [
{
"id": 1,
"question": "What is Salmon about?",
"answer": "Building great sites for our amazing clients. Simple."
},
{
"id": 3,
"question": "What is the location of Salmon Watford?",
"answer": "Just 2 minutes walk from Watford Junction Train Station"
},
{
"id": 5,
"question": "Is this the last question?",
"answer": "Yes. You have done well!"
}
]
}
例如,我需要将第一个问题和答案显示在第一个 <div>
中,第二个问题及答案<div>
以及第三个中的第三个问答<div>
.
我正在使用 AJAX 访问文件:
$.ajax({
url: 'faqs.json',
dataType: 'json',
type: 'GET',
cache: true,
success: function(data) {
$(data.faqs).each(function(index, value) {
$('#firstQuestion').text("Q: " + value.question);
$('#firstAnswer').text(value.answer);
$('#secondQuestion').text("Q: " + value.question);
$('#secondAnswer').text(value.answer);
$('#thirdQuestion').text("Q: " + value.question);
$('#thirdAnswer').text(value.answer);
});
}
});
现在我得到了一些结果,循环遍历所有项目并给出最后一个结果,但正如我之前所说,我需要第一个问题和答案 <div>
等等。
您能给我一些想法或解决方案吗?我花了大约 4 个小时试图解决这个问题,但我一无所获。非常感谢任何帮助。
最佳答案
你不需要循环 - 如果你不确定数组的长度,这将不起作用,你将需要一个不同的解决方案,如@usman-rana发布的,但如果你不这样做,这应该起作用:
$.ajax({
url: 'faqs.json',
dataType: 'json',
type: 'GET',
cache: true,
success: function(data) {
$('#firstQuestion').text("Q: " + data.faqs[0].question);
$('#firstAnswer').text(data.faqs[0]..answer);
$('#secondQuestion').text("Q: " + data.faqs[1]..question);
$('#secondAnswer').text(data.faqs[1].answer);
$('#thirdQuestion').text("Q: " + data.faqs[2].question);
$('#thirdAnswer').text(data.faqs[2].answer);
}
});
关于javascript - 如何从 JSON 文件中仅获取第一个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318059/