javascript - 如何从 JSON 文件中仅获取第一个属性?

标签 javascript jquery json ajax

我试图从此 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/

相关文章:

python - Json.dump 失败并出现 'must be unicode, not str' TypeError

javascript - Angular 教程不适用于 fiddle

javascript - 选择选项显示输入 block 并输入计数并自动显示另一个输入值的值

javascript - 在 Twitter Bootstrap 3 中切换类时的过渡

javascript - 将 html 内容包装在一个 div 中

php - 如何通过ajax将mysql结果作为jSON传递

javascript - 从外部 URL 下载文本文件

javascript - 如何使用JQUERY使用Mouseover/TouchStart/Mouseend/touchend创建圆形动画图像?

javascript - Ajax 请求有时会失败——使用和不使用 jQuery

ruby-on-rails - Rails中的RESTful内容协商