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

kus*_*tus 7 php jquery json

这是我在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);
?>
Run Code Online (Sandbox Code Playgroud)

客户端代码是:

$.post(url, {ID:$('#ddlClients').val()},
        function(Result){
            // Result
        }
      );
Run Code Online (Sandbox Code Playgroud)

AJAX调用已成功完成.我得到的值,结果

"{"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);
Run Code Online (Sandbox Code Playgroud)

要么

$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);
Run Code Online (Sandbox Code Playgroud)

有没有办法$row直接发送到客户端JavaScript并准备用作JSON对象,而无需先手动创建数组?

Jas*_*per 16

您从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
        }
    }
  );
Run Code Online (Sandbox Code Playgroud)

您可以通过将dataTypeAJAX调用的属性设置为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
        }
    }
  );
Run Code Online (Sandbox Code Playgroud)

以上示例期望服务器的响应采用此格式(来自您的问题):

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
Run Code Online (Sandbox Code Playgroud)


Tim*_*ers 5

在您的$.post调用中,最后一个参数可能是数据类型json::

$.post(url, {ID:$('#ddlClients').val()},
    function(Result){
        alert(Result.Address_1);
    },'json'
 );
Run Code Online (Sandbox Code Playgroud)

一切都应该正常工作,因为看起来你做的一切都是正确的。