我有一个html表单中的两个组合框,它们将使用jQuery和PHP从我的数据库中动态填充。当其中一个组合框被更改时,我调用我的jQuery,并将更改的组合框的值发送到我的php页面,以便从我的数据库中查找值。
function valueChanged(department){
$.get("AdminAjax.php",$("#department").serializeArray(),
function(data){
alert(data);//debug code that ouputs the returned value
var i =0;
for(i=0; i < data.length; i++){
//create a string that will be appended into the second combo box.
var option = '<option value="' + data.Category[i] +
'">=' + data.Category[i] + '</option>';
$("#category").append(option);
}
},"html" //debug for the return
);
}
我知道组合框的值是基于php页面的试错而传递的。
<?php
$department = mysql_real_escape_string($_GET["department"]);
//$department is the value passed from the jQuery.
$categorySQL = "Select Category from pagedetails where Department = '$department'";
//get the values for the second combo box based on the department
$rs = mysql_query($categorySQL);//<---this is where it fails.
//I have echoed out $rs and $rowCategory after I have fetched it.
//They return Resource #4 and Array respectively.
while($rowCategory = mysql_fetch_assoc($rs)){
//I am expecting multiple records to be returned.
$json_out = json_encode($rowCategory);
}
echo $json_out;
?>
答案 0 :(得分:1)
你的回答错误,你的php是错误的,你需要每次while为真时使用$.getJSON或$.ajax而不是$.get. You are resetting the
$ json_out`变量。您应该将所有值保存到数组中,然后对其进行json_encode一次。这也将确保你的json成功是有效的json。
试试这个:
$json_out = array();
while($rowCategory = mysql_fetch_assoc($rs)){
//I am expecting multiple records to be returned.
$json_out[] = $rowCategory;
}
echo json_encode($json_out);
答案 1 :(得分:1)
您在每次抓取时都会覆盖$json_out
。
而是尝试:
$json_out = array();
while($rowCategory = mysql_fetch_assoc($rs)){
$json_out[] = $rowCategory;
}
echo json_encode($json_out);