下拉填充ajax [英] Dropdown populate ajax
问题描述
我有以下问题:当我从下拉列表中选择一个元素时,我想通过 ajax 自动填充另一个下拉列表.这个想法是在选择类型"后不会加载子类别(sub_type).
I have the following issue: When i select an element from a drop down i want to auto populate another drop down via ajax. the idea is that the subcategory(sub_type) doesn't load after selecting the "type".
HTML
<select id="type" name="type">
<option value="1">General</option>
<option value="2">Test</option>
</select>
<select id="sub_type" name="sub_type">
</select>
SCRIPT
$("#type").change(function(){
$.getJSON("ajax/add_subcathegory.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id+ '">' + j[i].name+ '</option>';
}
});
$("#sub_type").html(options);
});
我的ajax脚本返回:
My ajax script returns:
[{id: 0, name: 'Mark'}, {id:1, name: 'Andy'}, {id:2, name: 'Richard'}]
但是子目录(第二个选择)没有加载.
But the subcathegory (secont select) isn`t loaded.
推荐答案
假设确实调用了Ajax成功函数,将函数代码改为:
Assuming that the Ajax success function is indeed called, change the function code to:
var $subType = $("#sub_type");
$subType.empty();
$.each(j, function () {
$subType.append($('<option></option>').attr("value", this.id).text(this.name));
});
您目前的主要问题是:
html
函数只被调用一次,因为它在成功函数之外.- Ajax 数据中的元素具有键 id 和 name 而不是 optionValue 和 optionDisplay莉>
- the
html
function is called only once because it's outside of the sucess function. - the elements in the Ajax data have the keys id and name and not optionValue and optionDisplay
更新:
返回的 JSON 无效.字符串必须用双引号引用,而不是单引号.因此,getJSON()
调用会以静默方式失败.
The returned JSON is invalid. String have to be quoted with double quotes, not single quotes. As a result, the getJSON()
call fails silently.
这篇关于下拉填充ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!