2012-03-02 9 views
1

jQueryとPHPを使用してデータベースから動的に読み込まれる2つのコンボボックスがHTMLフォームにあります。コンボボックスの1つが変更されたときに私の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で間違っている間違っていると、あなたは、変数$ $.get. You are resetting the json_out`するのではなく、しばらくは真であるたびに$.getJSON$.ajaxを使用する必要があります。すべての値を配列に保存してから、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

1

あなたがフェッチ各行に$json_outを上書きしています。

代わりにしてみてください:

$json_out = array(); 
while($rowCategory = mysql_fetch_assoc($rs)){ 
    $json_out[] = $rowCategory; 
} 
echo json_encode($json_out); 
関連する問題