2012-03-02 46 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);