尽管还有其他类似的示例,但我无法完全让每个循环都填充选择列表......但我真的很接近!
根据我的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 可以工作;但为什么这个学习列表不起作用对我来说仍然是个谜......感谢任何帮助!
最佳答案
看起来附录中有一些拼写错误,在 javascript 中,句点不用于集中,即 PHP,而在 javascript 中,句点将是 +
符号。
首先尝试创建元素,这样可以更轻松地查看正在发生的情况,然后附加它:
$.each(data, function(i, record) {
var elem = $('<option />', {value: record.studyindex, html: record.studyname});
$studylist.append(elem);
});
关于jquery - 如何迭代这个 json 数组并填充选择列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13828925/