2015-07-21 94 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