2015-07-21 93 views
1

我試圖從數據庫中讀取一些問題和答案。問題將作爲文本寫入頁面,而答案將是一個下拉菜單。即你最喜歡的顏色是什麼?藍色,綠色等。我的問題是他們沒有以正確的順序出現。我調用getData函數,它進入一個循環並獲得每個問題的答案。它進入getAnswers函數,但不進入嵌入函數。它返回到getData函數並在進入函數並獲取答案之前完成所有問題。這會導致所有問題被打印出來,然後是所有答案。我希望它成爲一個問題,然後是答案等等。我試圖擺脫額外的功能,並將所有功能放入一個功能,但它仍然無法正常工作,導致代碼難以閱讀。我認爲這是由JavaScript的函數回調引起的,但是對JavaScript的確切瞭解還不夠。任何幫助,將不勝感激。JavaScript函數回調

function getData(){ 
      $.getJSON("questions.php", "", 
       function(data) { 
        $.each(data, function(key, val) { 
         $("#divButton").append($('<p>' + val.question + '</p>')); 
         getAnswers(val.questionID); 

        }); 
       } 
      ); 
     } 

function getAnswers(questionID){ 
      //Gets to here when first called 
      $.getJSON("answers.php",{id:questionID}, 
       function(data){ 
        //Doesn't get to here until all questions have been written to page 
        var string = "<select>"; 
        $.each(data, function(key, val) { 
         string += "<option>" + val.answer + "</option>"; 
        }); 
        string += "</select></br>"; 
        $("#divButton").append($(string)); 
       } 
      ); 
     } 
+0

問題是$ .getJson是一個異步操作。它確實發生了,但是你的函數已經返回了。 –

回答

0

你已經寫了所有的問題後,返回處理程序getAnswers會發生。

一種解決方案是在提問元素通過,所以getAnswers知道該往哪兒插結果:

function getData(){ 
      $.getJSON("questions.php", "", 
       function(data) { 
        $.each(data, function(key, val) { 
         var question = $('<p>' + val.question + '</p>') 
             .appendTo($('#divButton')); 
         getAnswers(val.questionID, question); 

        }); 
       } 
      ); 
     } 

function getAnswers(questionID, questionElement){ 
      //Gets to here when first called 
      $.getJSON("answers.php",{id:questionID}, 
       function(data){ 
        //Doesn't get to here until all questions have been written to page 
        var string = "<select>"; 
        $.each(data, function(key, val) { 
         string += "<option>" + val.answer + "</option>"; 
        }); 
        string += "</select></br>"; 
        $(string).insertAfter(questionElement); 
       } 
      ); 
     } 
+0

謝謝,這工作! – Dylan