2017-01-10 33 views
0

我在我的主html頁面上有一個getJSON函數。 ID是一個整數,我試圖傳遞給PHP(JSON編碼)用作我的常見問題解答陣列中的一個鍵。我想知道如何引用傳入php的字符串(1,2或3)來使用它。如何在json中引用getJSON的數據參數?

的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." 
     } 
     ] 
    } 
} 
+0

如果您沒有注意到,我已經爲您的問題發佈了一個答案! – EhsanT

回答

0

假設你已經在json format像正確設置id變量:var id = {id: 5};

而且在基於JSON結構y你已經發布了,你有一個節點faqs。所以首先你必須這樣做:var faqs = data.faqs;然後遍歷這個對象。

您還在每個節點至少有1對問答,因此最好爲它們創建兩個不同的<div>,然後將它們附加到每個問題的另一個<div>。而且我注意到你在第一個FAQ中有2對Q和A,所以你必須有一個內部循環來循環我在這一行所做的每個FAQ的Q和A列表:for(iCnt = 0; iCnt < faq.length; iCnt++){

最終的代碼如下所示:

var id = {id: 5}; // Just in case you need a correct format 

$.getJSON("faqs.php", id, function(data){ 
    var faqs = data.faqs; 
    $.each(faqs, function(faqId, faq){ 
     $('<div/>') 
      .attr('id', 'faq'+faqId) 
      .addClass("list-group-item") 
      .appendTo($("#topic-container")); 

     for(iCnt = 0; iCnt < faq.length; iCnt++){ 
      var q = $('<div/>') 
       .attr('id', 'q-'+faqId+'-'+iCnt) 
       .text(faq[iCnt].question) 
       .appendTo('#faq'+faqId); // div for each question 

      var a = $('<div/>') 
       .attr('id', 'a-'+faqId+'-'+iCnt) 
       .text(faq[iCnt].answer) 
       .appendTo('#faq'+faqId); // div for each answer 
     } 
    }); 
});