下拉填充ajax
我有以下问题:当我从下拉列表中选择一个元素时,我想通过 ajax 自动填充另一个下拉列表。这个想法是,选择“类型”后,子类别(sub_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 脚本返回:
[{id: 0, name: 'Mark'}, {id:1, name: 'Andy'}, {id:2, name: 'Richard'}]
但子类别(第二个选择)未加载。
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);
});
My ajax script returns:
[{id: 0, name: 'Mark'}, {id:1, name: 'Andy'}, {id:2, name: 'Richard'}]
But the subcathegory (secont select) isn`t loaded.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设确实调用了 Ajax success 函数,请将函数代码更改为:
您当前的主要问题是:
html
函数仅被调用一次,因为它位于 success 函数之外。更新:
返回的 JSON 无效。字符串必须用双引号引起来,而不是单引号。因此,
getJSON()
调用会默默失败。Assuming that the Ajax success function is indeed called, change the function code to:
Your main problems currently are:
html
function is called only once because it's outside of the sucess function.Update:
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 JSON 调用之后立即将 html 分配给 #sub_type 。您应该在 ajax 回调函数中分配它,如下所示:
The problem is, that you are assigning the html to #sub_type right after the ajax JSON call. You should assign it in the ajax callback function like this: