【发布时间】:2012-01-28 19:04:35
【问题描述】:
这是我在 jQuery AJAX 调用期间调用的 PHP 代码:
<?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 调用已成功完成。我将 Result 的值设为
"{"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 对象,而无需先手动创建数组?
【问题讨论】:
-
我不知道您是否可以这样做,但这可能对您有用。 stackoverflow.com/questions/383631/json-encode-mysql-results