如何在json中引用getJSON的数据参数?

时间:2017-01-10 22:11:16

标签: php json

我的主html页面上有一个getJSON函数。 id是一个整数,我试图传递给php(json编码),用作下面我的faqs数组中的一个键。我想知道如何引用传递给php的字符串(1,2或3)来使用它。

getJSON代码:

$.getJSON("faqs.php", id, function(data){
//$.getJSON("faqs.php?topic=field", function(data) {
    if(data == "") {
        $("<div>", {class: "list-group-item", text: "Please add FAQs."}).appendTo($("#topic-container"));
    }
    $.each(data, function(faqId, faq){
        $("<div>", {id: "faq" + faqId, class: "list-group-item", text: faq}).appendTo($("#topic-container"));
    });
});

faqs.php

header('Content-Type: application/json; charset=utf-8');

{"faqs":
    {"1":[
        {
        "question": "What is the best musical instrument in the world?",
        "answer": "The English concertina"
        },
        {
        "question": "How many double bass players does it take to change a light bulb?",
        "answer": "None, the piano player can do that with his left hand."
        }
        ],
      "2":[
        {
        "question": "Why do programmers confuse halloween and christmas?",
        "answer": "Because Oct 31 = Dec 25."
        }
        ],
     "3":[
        {
        "question": "Should I eat more pizza?",
        "answer": "Yes. Always."
        }
        ]
    }
}

1 个答案:

答案 0 :(得分:0)

假设您已在id中正确设置json format变量,例如:var id = {id: 5};

根据您发布的json结构,您有一个节点faqs。所以首先你必须得到这样的结果:var faqs = data.faqs;然后遍历这个对象。

每个节点中您还有至少1对问答,因此最好为它们创建两个不同的<div>,然后将它们附加到另一个问题的<div>。我注意到你在第一个常见问题解答中有2对Q和A,所以你必须有一个内部循环来遍历我在这一行中所做的每个常见问题解答的Q和A列表:{{1 }}

最终代码如下所示:

for(iCnt = 0; iCnt < faq.length; iCnt++){