jQuery ajax调用以设置MySql表中的选择选项 [英] jquery ajax call to set select options from a MySql table
问题描述
我有一个DDL(#engine),需要根据所选的#make ddl通过MySql表设置其选项值.
I have a DDL (#engine) that needs to have its option values set via a MySql table based on the selected #make ddl.
我有以下脚本传递给php文件-我知道该php文件很好,因为我可以独立输出查询结果.
I have the below script which passes to a php file - I know the php file is fine as I can output the results of the query independantly.
但是,我无法获得基于返回的数组进行更新的选项值...也许是使用GET的结果?这是我第一次尝试通过AJAX返回(通常仅使用它来更新数据表等).
But, I cannot get the option values to update based on the returned array ... maybe a result of using GET? It's the first time i'm trying to return via AJAX (usually just use it to update data tables etc.)
我的脚本中有什么不对吗?
Is there something amiss in my script?
$(document).ready(function() {
$("select#make").change(function(){
$('#engine').find('option').remove().end(); //clear the engine ddl
var make = $(this).find("option:selected").val(); //Need the value not the text
$.ajax({
url:'get-engine.php',
type:'GET',
data:{engine:make},
dataType:'json',
cache:false,
success:function(data){
var ddl = document.getElementById('engine');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
});
和get-engine.php ..
$make = $_GET['engine'];
$query= ("SELECT * FROM tb_engine where make_id='$make'");
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['engine_type']);
}
else
{
array_push($temp,$row['engine_type']);
}
}
echo (json_encode($temp));
?>
到目前为止,它拒绝更新,找不到原因吗?
It so far refuses to update, can't quite find why?
提前感谢所有建议
推荐答案
您可以尝试
//json is the json you have recieved in the success handler
$("#engine").empty();
$.each( json, function( index, item ) {
$("<option/>",{value:item,text:item}).appendTo("#engine");
});
这篇关于jQuery ajax调用以设置MySql表中的选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!