简体   繁体   中英

JSON can't read returned ajax value

I have an ajax function that retrieve two values for a given post: one for the number of likes, another one for the div that contains all the people that liked that post.

Everything seems to work fine, the json retrieved is correct, but the printing result is incorrect. Every time I try to get the number of likes ( data.numDiLikes ) I always get undefined even though the json is saying {"numDiLikes":"1","personeACuiPiace":"div info and stuff"} , how do I fix this?

AJAX with JSON

$.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;

}

Use dataType: "json" to tell $.ajax that it returns JSON, and that it should parse it. dataType: "html" means that it returns HTML text, and data will be a string, not an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM