Getjson Return Data
Here is my code: var name; function getFBName(username) { $.getJSON('http://graph.facebook.com/' + username, function (d) { name = d.name; }); } getFBName('zuck');
Solution 1:
As @jwatts1980 said, this is a matter of order of execution. $.getJSON
will return immediately, before the response has arrived to the client, so when you run console.log
, it will still be waiting. One possible solution is:
functiongetFBName(username) {
$.getJSON('http://graph.facebook.com/' + username, function (d) {
console.log(d.name);
});
}
getFBName("zuck");
Which will log Mark Zuckerberg
correctly. If you have multiple ways of handling the output, it may also be interesting to set a callback
function:
functiongetFBName(username, callback) {
$.getJSON('http://graph.facebook.com/' + username, function (d) {
callback(d.name);
});
}
functionhandleName(name) {
// Do a lot of things hereconsole.log(name);
}
getFBName("zuck", handleName);
Post a Comment for "Getjson Return Data"