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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8649621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:10:19  来源:igfitidea点击:

Returning a JSON object from PHP in AJAX call?

phpjqueryjson

提问by Kumar Kush

Here's my PHP code called during jQuery 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);
?>

And the client-side code is:

客户端代码是:

$.post(url, {ID:$('#ddlClients').val()},
        function(Result){
            // Result
        }
      );

The AJAX call is successfully completed. I get the value of Resultas

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

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on

"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on

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.

我想要的是能够使用返回的值,如 Result.Address_1、Result.Address_2 等。但是我不能使用上面的代码来做到这一点。我尝试使用$row = $result->fetch_object()and $row = $result->fetch_array(),但没有用。

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);

or

或者

$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);

Is there a way to send the $rowdirectly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?

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

回答by Jasper

The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSONin your callback function:

您从 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
        }
    }
  );

You can let jQuery do this for you by setting the dataTypeproperty for your AJAX call to json:

您可以通过将dataTypeAJAX 调用的属性设置为 ,让 jQuery 为您执行此操作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"}

回答by Tim Withers

In your $.postcall, the last argument could be the data-type: json:

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

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

Everything should work then, as it looks like you are doing everything right.

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

回答by Lightness Races in Orbit

json_encodeaccepts objects, so there's no need to do that automatic array-building.:

json_encode接受对象,因此无需进行自动数组构建。:

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

It's as simple as that!

就这么简单!