2011-12-27 76 views
6

這裏是我的jQuery AJAX調用期間調用PHP代碼:在AJAX調用中從PHP返回JSON對象?

<?php 
    include '../code_files/conn.php'; 
    $conn = new Connection(); 
    $query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2 
       FROM clients WHERE ID = ?'; 
    $conn->mysqli->stmt_init(); 
    $stmt = $conn->mysqli->prepare($query); 
    $stmt->bind_param('s', $_POST['ID']); 
    $stmt->execute(); 
    $result = $stmt->get_result(); 
    $row = $result->fetch_assoc(); 
    echo json_encode($row); 
?> 

和客戶端代碼:

$.post(url, {ID:$('#ddlClients').val()}, 
     function(Result){ 
      // Result 
     } 
    ); 

AJAX調用成功完成。我得到的結果值作爲

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on

我要的是能夠使用返回的值一樣Result.Address_1,Result.Address_2等。但是我不能用上面的代碼來做。我試過使用$row = $result->fetch_object()$row = $result->fetch_array(),但沒用。

而且我知道,這可以通過這個代碼在服務器端完成:

$row = $result->fetch_assoc(); 
$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......); 
echo json_encode($retVal); 

$row = $result->fetch_object(); 
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......); 
echo json_encode($retVal); 

有沒有辦法直接發送$row到客戶端JavaScript並準備用作JSON對象,而無需首先手動創建數組?

+1

我不知道你是否可以這樣做,但這可能對你有用。 http://stackoverflow.com/questions/383631/json-encode-mysql-results – insomiac 2011-12-27 21:53:34

回答

16

您從PHP腳本獲得的響應是​​純文本格式。但是,您可以解析字符串轉換成在回調函數使用$.parseJSON對象:

$.ajax({ 
    url  : url,//note that this is setting the `url` property to the value of the `url` variable 
    data  : {ID:$('#ddlClients').val()}, 
    type  : 'post', 
    success : function(Result){ 
      var myObj = $.parseJSON(Result); 
      //you can now access data like this: 
      //myObj.Address_1 
     } 
    } 
); 

可以讓jQuery的通過爲AJAX調用設置dataType屬性json爲你做這個:

$.ajax({ 
    url  : url//note that this is setting the `url` property to the value of the `url` variable 
    data  : {ID:$('#ddlClients').val()}, 
    dataType : 'json', 
    type  : 'post', 
    success : function(Result){ 
      //you can now access data like this: 
      //Result.Address_1 
     } 
    } 
); 

在上面的例子中預計,從服務器的響應是這一格式的文件(你的問題):

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"} 
+0

謝謝。你的技術也有效。 – 2011-12-27 22:03:12

+0

是的。響應格式與您所提到的相似。但我沒有解析它。 – 2011-12-27 22:09:07

4

在您的通話$.post,最後一個參數可以是數據類型:json

$.post(url, {ID:$('#ddlClients').val()}, 
    function(Result){ 
     alert(Result.Address_1); 
    },'json' 
); 

一切都應該工作,然後,因爲它看起來像你的權利做的一切。

+0

謝謝。這工作。我認爲$ .post()會自動轉換來自服務器的響應。 – 2011-12-27 22:02:20

2

json_encode接受對象,所以沒有必要這樣做自動陣列建設:

$row = $result->fetch_object(); 
echo json_encode($row); 

就這麼簡單!

+0

你可以看到我的問題。我已經做到了。我所缺少的是我在進行AJAX調用時沒有指定類型'json'。 – 2011-12-27 22:06:47

+0

不,您創建了手動數組,所以我回答了問題:「有沒有辦法將$行直接發送到客戶端JavaScript並準備用作JSON對象,_而不是首先手動創建數組?_」 – 2011-12-27 22:10:41

+0

對不起,但看看我的問題中的第一塊代碼。我曾嘗試過你提到過的。兩種方式,我不得不解析jQuery中的答覆。不管怎麼說,多謝拉。 – 2011-12-27 22:16:49