這裏是我的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對象,而無需首先手動創建數組?
我不知道你是否可以這樣做,但這可能對你有用。 http://stackoverflow.com/questions/383631/json-encode-mysql-results – insomiac 2011-12-27 21:53:34