单独打印JSON数据


Print JSON Data Individually

我有一个AJAX请求,它本质上是查询数据库,然后将数据发布回JS,但我不能打印单独的数据。

我的代码如下:

$.ajax({
            type: 'POST',
            url: '_process/offerrespres.php',
            dataType: 'json',
            data: {
                msgid: msgid,
                usrid: usrid
            },
            success: function(){
                console.log(JSON.parse(data.pro_name));
                console.log(data.accept_decline);
            }
        });

PHP:

<?php
include_once 'connect.php';
if ($_POST) {
$msgid = mysql_escape_string($_POST['msgid']);
$usrid = mysql_escape_string($_POST['usrid']);  
$getmsgq = mysql_query("SELECT * FROM booking_requests WHERE receiver_id = '$usrid' AND msg_id = '$msgid'");
$getmsg_info = mysql_fetch_array($getmsgq); 
$data['success'] = true;
$data['date_sent'] = $getmsg_info['date_sent'];
$data['pro_name'] = $getmsg_info['pro_name'];
$data['accept_decline'] = $getmsg_info['accept_decline'];
}
header("Content-Type: application/json", true);
echo json_encode($data);
mysql_close();
?>

正如你所看到的,我已经尝试过这个:

console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);

控制台中的错误显示"数据未定义"。PHP文件的输出是正确的,应该是正确的。我只是不能打印一条数据。

您的回调函数不接受返回数据作为参数

读取success: function(){的行应该是success: function(data){

此外,在呼叫header("Content-Type: application/json", true);时不需要true。此函数的默认操作是替换标头,因此true已被隐含。只有当您不想替换以前的Content-Type时,该参数才是必需的。对您的代码没有任何影响,只是一个提示。

您没有在success函数中指定数据变量。应该是:

success: function(data){
   console.log(JSON.parse(data.pro_name));
   console.log(data.accept_decline);
}