GetJSON返回数据 [英] GetJSON return data

查看:106
本文介绍了GetJSON返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

var name;
function getFBName(username) {
    $.getJSON('http://graph.facebook.com/' + username, function (d) {
        name = d.name;
    });
}
getFBName("zuck");
console.log(name);

几个小时以来我一直在努力,但是我无法获得getFBName函数来返回用户名.

I am struggling since hours but I can't get the getFBName function to return the name of the user.

这是JSON btw:

This is the JSON btw:

{
   "id": "4",
   "first_name": "Mark",
   "gender": "male",
   "last_name": "Zuckerberg",
   "link": "https://www.facebook.com/zuck",
   "locale": "en_US",
   "name": "Mark Zuckerberg",
   "username": "zuck"
}

推荐答案

正如@ jwatts1980所说,这是执行顺序的问题. $.getJSON将在响应到达客户端之前立即返回,因此,当您运行console.log时,它将仍在等待.一种可能的解决方案是:

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:

function getFBName(username) {
    $.getJSON('http://graph.facebook.com/' + username, function (d) {
        console.log(d.name);
    });
}
getFBName("zuck");

这将正确记录Mark Zuckerberg.如果您有多种处理输出的方法,则设置callback函数也可能很有趣:

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:

function getFBName(username, callback) {
    $.getJSON('http://graph.facebook.com/' + username, function (d) {
        callback(d.name);
    });
}

function handleName(name) {
    // Do a lot of things here
    console.log(name);
}

getFBName("zuck", handleName);

这篇关于GetJSON返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆