![](/img/trans.png)
[英]Returning php associative array from function to ajax call with json_encode() not and object
[英]Returning a JSON object from PHP in AJAX call?
這是我在 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 對象,而無需先手動創建數組?
您從 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
}
}
);
您可以通過將 AJAX 調用的dataType
屬性設置為json
來讓 jQuery 為您執行此操作:
$.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"}
在您的$.post
調用中,最后一個參數可能是 data-type: json
:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
alert(Result.Address_1);
},'json'
);
一切都應該正常工作,因為看起來你做的一切都是正確的。
json_encode
接受對象,因此無需進行自動數組構建。:
$row = $result->fetch_object();
echo json_encode($row);
就這么簡單!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.