如何在ajax成功函数中打印json


How can I print json in my ajax success function

我正在从服务器返回json,但它在ajax中的成功回调中不可用。

$.ajax({
    url:'myData.php',
    type:'post',
    success:function(data){
        console.log(data.name); // This should print my name
    }
});

在php中,我使用这个

$data=array('id' => 1, 'name' => 'john');
echo json_encode($data);

我错过了什么?

任一

  1. 告诉jQuery您希望返回JSON数据。请参阅上的dataTypehttp://api.jquery.com/jQuery.ajax/

  2. 返回一个标头,以便jQuery可以将响应检测为JSON:

     header('Content-type: application/json');