2012-07-20 136 views
1

我有txt_RollNoblur事件AJAX調用帶來std_nameClassage從數據庫中txt_nametxt_classtxt_age填充它。阿賈克斯PHP的jQuery

在一個調用中,我可以讓name,class,age作爲一個整體在數組或任何,如何分離它。

$("#txt_RollNo").blur(function(){ 
$.ajax({ 
      url:'getSudent.php', 
      data:'stdID='+ $(this).val().trim(), 
      success:function(array_from_php) 
      { 
      //but here i m receiving php array, how deal in jquery 
       //$("#txt_name").val(array_from_php); 
       //$("#txt_Class").val(array_from_php); 
       //$("#txt_age").val(array_from_php); 

      } 
      }) 
}); 

getSudent.php回聲陣列如下面

<?php 
    $qry=mysql_query("select * from students where studentID='".$_GET['std_ID']."'"); 
    $row=mysql_fetch_array($qry); 
    echo $row; 
?> 

回答

3

PHP:

<?php 
    header('Content-type: application/json'); 
    $qry=mysql_query("select * from v_shop where shop_no='".$_GET['shopno']."'"); 
    $row=mysql_fetch_array($qry); 
    echo json_encode($row); 
?> 

的JavaScript

... 
$.ajax({ 
    dataType: 'json', 
    ... 
    success:function(array_from_php){ 
     console.log(array_from_php); // WTF is this? 

見json_encode:http://php.net/manual/en/function.json-encode.php

+1

確保添加你需要'數據類型: 'json'在你的AJAX調用中,'array_from_php'現在是一個對象。 – 2012-07-20 15:45:09

+0

@火箭文檔說:「dataType - 默認值:**智能猜測**(XML,** JSON **,腳本或HTML)」http://api.jquery.com/jQuery.ajax/ – iambriansreed 2012-07-20 15:48:14

+0

這只是如果你輸出你的PHP爲'Content-type:application/json'。否則,jQuery將其視爲文本。 – 2012-07-20 15:49:08

3

首先在php將其作爲JSON:

echo json_encode($row); 

然後只把它當作任何數組:

$("#txt_RollNo").blur(function(){ 
$.ajax({ 
     url:'getSudent.php', 
     data:'stdID='+ $(this).val().trim(), 
     dataType : 'json', 
     success:function(array_from_php) 
     { 
      // i suggest you output the array to console so you can see it 
      // more crearly 
      console.log(array_from_php); 
      $("#txt_name").val(array_from_php[0]); 
      $("#txt_Class").val(array_from_php[1]); 
      $("#txt_age").val(array_from_php[2]); 

     } 
     }) 
}); 
+1

這不僅僅是一個神奇的陣列。你需要讓PHP輸出它('json_encode')。 – 2012-07-20 15:46:49

+1

對不起,我在編輯我的代碼: – 2012-07-20 15:47:44

+0

'array_from_php.name'會比'array_from_php [0]'更好嗎? – 2012-07-20 15:49:55