从PHP中以AJAX调用返回JSON对象?

9

以下是我在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对象,而不需要手动创建数组?

1
我不知道你是否能够做到这一点,但这个链接对你可能会有用。https://dev59.com/CXRC5IYBdhLWcg3wMd9S - insomiac
3个回答

18
您从 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"}

是的,响应格式就像你所提到的那样。但我没有解析它。 - Kumar Kush

5
在您的$.post调用中,最后一个参数可以是数据类型:json:
$.post(url, {ID:$('#ddlClients').val()},
    function(Result){
        alert(Result.Address_1);
    },'json'
 );

一切应该正常工作,因为看起来你做得很正确。


谢谢。那个有效。我以为 $.post() 会自动转换来自服务器的响应。 - Kumar Kush

3

json_encode可以接受对象,因此不需要进行自动数组构建。

$row = $result->fetch_object();
echo json_encode($row);

就是这么简单!

你可以看到我的问题。我已经完成了。我之前缺少的是在发起 AJAX 调用时没有指定类型为“json”。 - Kumar Kush
不,因为您手动创建了该数组,所以我回答了这个问题:“有没有一种方法可以直接将 $row 发送到客户端 JavaScript 并准备好用作 JSON 对象,而无需先手动创建一个数组?” - Lightness Races in Orbit
抱歉,但请看一下我问题中的第一个代码块。我也尝试了你提到的方法。无论哪种方式,我都必须在jQuery中解析响应。不管怎样,还是谢谢。 - Kumar Kush
你的问题似乎有误,因为最终你并不需要关于带问号的那个句子的帮助。 - Lightness Races in Orbit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接