gpt4 book ai didi

php - 在 AJAX 调用中从 PHP 返回一个 JSON 对象?

转载 作者:可可西里 更新时间:2023-11-01 12:42:57 31 4
gpt4 key购买 nike

这是我在 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",.....等等

我想要的是能够使用像 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"}

关于php - 在 AJAX 调用中从 PHP 返回一个 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8649621/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com