2012-03-02 69 views
1

我有两个组合框,它们将以html形式从数据库中使用jQuery和PHP动态填充。当其中一个组合框发生变化时,我会调用我的jQuery,并将更改后的组合框的值发送到我的php页面,以便从我的数据库中查找值。AJAX:没有从数据库中获取关联数组

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; 
?> 

回答

1

您的回音是错在你的PHP是错误的,你需要在每次当为真时使用$.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); 
+0

$就奏效了。我也切换到输出一个字符串,如''在while循环中。 – Thoross 2012-03-16 14:05:08

1

你覆盖$json_out每行获取。

而是尝试:

$json_out = array(); 
while($rowCategory = mysql_fetch_assoc($rs)){ 
    $json_out[] = $rowCategory; 
} 
echo json_encode($json_out);