简体   繁体   中英

Retrieve data from PHP file using $.getJSON

I'm trying to set up a comments system on photos.


I understand how to use $.getJSON when the array is like this:

get.php:

$var = 5;
echo json_encode(array('var'=>$var));

main.php:

$.getJSON("get.php",function(data){
    number = data.var; // number = 5
});

But I have a more complex thing.


My comments table has these 4 columns: id | photo_id | comment | date

For example let's say we're trying to retrieve the comment data from the photo with

photo_id == 1 .

We don't know how many comments there might be.

In getcomments.php:

$photoid = 1;

$comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");

while($commentrow = $comment->fetch_assoc()) {
    $comments[] = $commentrow;
}

Then you encode it:

echo json_encode($comments);

Which prints something like this (the photo has 2 comments):

[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]

How do I declare variables for the comments array?

$.getJSON("getcomments.php",function(data){
    // how do I declare variables for the comments array, especially since you don't know how many there might be?
});

Additionally, I have two json arrays that need to be echoed within the same PHP file. ie echo json_encode(array('img1'=>$img1link)) and echo json_encode($comments); need to be echoed within the same PHP file, but it made the code stop working altogether.

If you want to display the comments you need to loop over the array. You can use for loop or forEach function.

$.getJSON("getcomments.php",function(data){
    data.forEach(function(comment) {
        $('div').append('<span>' + comment.comment + '</span>');
    });
});

To display two JSONs you need to combine them into one JSON object.

echo json_encode(array('img' => $img1link, 'comments' => $comments));
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]

Using this JSON, data is an array and you should manage it as an array. You can loop through it using simple loops ( for , while ...) or using new functional methods like forEach , map , filter ....

Please try with this example:

$.getJSON("getcomments.php",function(data){
    data.forEach(function(item, index, all) {
        console.log(item.comment);
    });
});

Declare an object, and push it to the array.

var commentsArr = [];

for (var i = 0; i < data.length; i++) {
    var objToPush = {
        id: data.id,
        comment: data.comment,
        date: data.date
    }

    commentsArr.push(objToPush);
}

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