在AJAX调用中从PHP返回JSON对象? [英] Returning a JSON object from PHP in AJAX call?
问题描述
这是我在jQuery AJAX调用期间调用的PHP代码:
Here's my PHP code called during jQuery AJAX call:
<?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调用成功完成.我将结果的值为
The AJAX call is successfully completed. I get the value of Result as
"{"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()
,但是没有用.
What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object()
and $row = $result->fetch_array()
, but no use.
我知道这可以通过服务器端的以下代码来完成:
And I know that this can be done by this code on the server side:
$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对象,而无需首先手动创建数组?
Is there a way to send the $row
directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?
推荐答案
从PHP脚本获得的响应为纯文本格式.但是,您可以在回调函数中使用$.parseJSON
将该字符串解析为一个对象:
The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON
in your callback function:
$.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为您完成此操作:
You can let jQuery do this for you by setting the dataType
property for your AJAX call to 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
}
}
);
以上示例期望服务器的响应采用以下格式(根据您的问题):
The above examples expect that the response from the server to be in this format (from your question):
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
这篇关于在AJAX调用中从PHP返回JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!