JSON无法读取返回的ajax值

时间:2015-12-09 22:08:05

标签: php json ajax

我有一个ajax函数可以为给定的帖子检索两个值:一个用于喜欢的数量,另一个用于包含喜欢该帖子的所有人的div

一切似乎工作正常,json记录是正确的,但打印结果不正确。每当我尝试获得喜欢的数量(data.numDiLikes)我总是得到undefined,即使json说{"numDiLikes":"1","personeACuiPiace":"div info and stuff"},我该如何解决?

使用JSON的AJAX

$.ajax({
    dataType: "json",
    type: 'POST',
    cache: false,
    url: "lib/ottieniCose.php",
    data: { like: "", id: valCOR, comOrisp: comOrisp },
    dataType: "html",
    success: function(data, textStatus){
        trova.find('.numDiLikes').first().replaceWith('<p class="numDiLikes">' + data.numDiLikes + ' mi piace</p>' + data.personeACuiPiace);
    }
});

PHP

if ($_POST['comOrisp'] == 'commento') {

        $commento->set_likes($_POST['id'], true);
    // number of people that liked the post
        $return_data['numDiLikes'] = $commento->get_likes($_POST['id'], true);
    // div with all the people who liked the post
        $return_data['personeACuiPiace'] = $commento->posso_fare_qualcosa($_SESSION['auth'], 'cancRisp', $_POST['id']);

    echo json_encode($return_data);exit;

}

1 个答案:

答案 0 :(得分:1)

使用dataType: "json"告诉$.ajax它返回JSON,并且它应该解析它。 dataType: "html"表示它返回HTML文本,data将是字符串,而不是对象。