如何迭代此json数组并填充选择列表?

时间:2012-12-11 21:38:47

标签: jquery json

尽管有其他类似的例子,但我不能完全理解每个循环来填充选择列表......但我真的很接近!

根据我的previous question,我使用PHP脚本返回一个json数组,基于另一个部分回答的问题。脚本getStudyNames.php返回这个json数组:

[{"studyindex":"1","studyname":"ADHD"},{"studyindex":"24","studyname":"ADHD_RD"},{"studyindex":"20","studyname":"AFL"},{"studyindex":"42","studyname":"AFRICANERS"},{"studyindex":"2","studyname":"AHD"},{"studyindex":"22","studyname":"AJS"},{"studyindex":"3","studyname":"ASA-FS"},{"studyindex":"4","studyname":"ASIAN"},{"studyindex":"5","studyname":"AUS TWINS"},...]

但是,我似乎无法正确解析如何解析此数组,然后将其添加到选择列表中。

以下是我的代码尝试执行此操作:

$.ajax({                                      
      url: 'getStudyNames.php',        //the script to call to get data          
      data: "",                        //you can insert url argumnets here to pass to api.php
                                       //for example "id=5&parent=6"
      dataType: 'json',                //data format
      error: function() {
        alert('Refresh of study names failed.');
      },
      success: function(data)          //on receipt of reply
      { 
        var $studylist = $('#studylist').empty();
        $data.each(data, function(i, record) {
          $studylist.append('<option value='.record.studyindex.'>'.html(record.studyname) );
        })
       } 
    });

我知道getStudyNames.php按照上面的输出工作;但为什么这个研究表不起作用对我来说仍然是一个谜......感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

看起来附加中有一些拼写错误,并且句点不用于javascript中的常规,即PHP,以及javascript中的+符号。

首先尝试创建元素,让它更容易看到发生了什么,然后追加它:

$.each(data, function(i, record) {
  var elem = $('<option />', {value: record.studyindex, html: record.studyname});
  $studylist.append(elem);
});

答案 1 :(得分:1)

$data.each(data, function)

应该是

$.each(data, function)

.html()未正确嵌套在.append()

您没有关闭<option>

'<option value='.record.studyindex.'>'

应该是

'<option value=' + record.studyindex + '>'

答案 2 :(得分:1)

尝试将以下内容放入success

var $studylist = $('#studylist').empty();
$.each(data, function(i, record) {
   $studylist.append($("<option/>", {
        value: record.studyindex,
        text: record.studyname
    }));
});