2013-02-11 121 views
0

我有一个AJAX请求,基本上查询数据库,然后将数据发布回JS,但是我无法打印单个数据位。单独打印JSON数据

我的代码如下:

$.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文件的输出是正确的,它应该如何,我不能打印一个单一的数据。

回答

3

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

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

而且,不需要在调用header("Content-Type: application/json", true);true。此功能的默认操作是替换标题,因此已暗示true。只有当你不想取代以前的Content-Type时,这个论点才是必要的。对你的代码没有影响,只是一个提示。

+0

谢谢 - 另一个简单的事情。工作过一种享受。此外,data.pro_name正常工作(没有JSON.parse) – 2013-02-11 13:32:35

+0

@Steve_M不客气。如果解决了您的问题,请将答案标记为已接受,以便其他人知道该问题已得到解答。 – 2013-02-11 13:33:15

0

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

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