下拉列表填充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'}]
但是没有加载subcathegory(secont select)。
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
函数只调用一次,因为它不在sucess函数内。 - Ajax数据具有密钥 id 和名称,而不是 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屋!