简体   繁体   中英

REST API, return JSON objects from PHP to JS file

I am writing some kind a rest API for the first time, so I need a little help. I found few solutions for my problems here on stackoverflow and I managed to solve them. But now I came to another one and could not find a solution.

First of all, js file code.

$.getJSON('test.php', function(data) {
    console.log(data);
    articles = data;
    return articles;            
});

This is js file, from which I send request to php file and then get data back. The thing is, data I get back from php looks fine in browser console when I log it, all data is there. But when I try to use that data on page (with my return statement), it does not work. If I replace return articles row with

return [{"name":'Name goes here',"description":'Description goes here'}];

it works fine on a page. This is bothering me, because in browser console I can see all the objects that have been returned from php file, but they do not work on page. I hope any of you can help me. I am pasting my php file below.

$json = array(
        array(
            "name" => 'Name goes here',
            "description" => 'Test description.',
            "link" => 'articles/articleName',
            "img" => '../images/article1.jpg'
        ),
        array(
            "name" => 'Name goes here 2',
            "description" => 'Not ready yet',
            "link" => '#',
            "img" => ''
        ),
        array(
            "name" => 'Name goes here 3',
            "description" => 'Not ready yet',
            "link" => '#',
            "img" => ''
        )
    );

    $jsonstring = json_encode($json, JSON_PRETTY_PRINT);
    echo $jsonstring;

The problem is you're returning in the async part of your $.getJson call.

What you have:

function myFunction()
{
    $.getJSON('test.php', function(data) {
        console.log(data);
        articles = data;
        return articles;            
    });
}
var articles = myFunction();

myFunction runs, and returns nothing, then later the $.getJSON gets its response and doesn't have anything to do with it.. Return doesn't mean much there since the code has 'moved on'

What you need to do is handle the data inside the async part of getJSON (or pass in a function to do stuff in there)

What you need:

function myFunction()
{
  $.getJSON('test.php', function(data) {
    console.log(data);
    articles = data;          

    //do something with articles
    //maybe set a div equal to them
    $("#myArticles").innerHTML = articles;

    //or call a function with articles as a param
    doSomethingCool(articles);
  });
}

function doSomethingCool(arts)
{
  alert("You have articles: " + arts);
}

You can even pass in the thing you want to do as a param

function myFunction(callback)
{
  $.getJSON('test.php', function(data) {
    console.log(data);
    articles = data;          

    callback(articles);
  });
}


myfunction(alert);  //will alert with the articles

//define the callback function 'on the fly'
myfunction(function(articlesFromJson) {
  if(articlesFromJson.length > 2)
    alert("wow 2+ arcticles");
});

The above would grab the articles twice, and do something different with the each time.

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