使用 jQuery 获取 JSON Facebook Graph API 用户信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6431576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:51:52  来源:igfitidea点击:

Get JSON Facebook Graph API User Info with jQuery

jqueryjsonfacebook-graph-api

提问by BillPull

I am trying to use the graph API to get just some basic info about a user no need for authorization by the user just the public details. I am trying to use jQuery and the .getJSON to get the data and parse it but I am having a hard time trying to figure out how to access the key value pairs I want.

我正在尝试使用图形 API 来获取有关用户的一些基本信息,无需用户授权,只需公开详细信息。我正在尝试使用 jQuery 和 .getJSON 来获取数据并解析它,但我很难弄清楚如何访问我想要的键值对。

I want to have something like

我想要类似的东西

var fburl = "http://graph.facebook.com/USER/callback=?"

$.getJSON(fburl, function(data){
  $.each(data, function(i,item){
     var name = item.user["name"];
     $("#profile").append("<h3>"name"</h3>");
  });
});

ive tried things like item.name and a bunch of other what I figured to be potential syntax options but still getting undefined.

我尝试了 item.name 和其他一些我认为是潜在的语法选项但仍然未定义的东西。

Is there anything wrong with this approach I only really have experience using JSON with twitter API which works fine with the above approach.

这种方法有什么问题吗我真的只有使用 JSON 和 twitter API 的经验,它可以很好地与上述方法配合使用。

When I console log data I get something like this

当我控制台日志数据时,我得到这样的信息

first_name: "First"
gender: "male"
id: "8977344590"
etc...
name: "Full Name"

采纳答案by Niklas

It doesn't return an array, but an object. You don't need to be looping over anything.

它不返回一个数组,而是一个对象。你不需要循环任何东西。

You can just get the name straight from the object:

您可以直接从对象中获取名称:

$.getJSON(fburl, function(data){
     var name = data["name"];
     $("#profile").append("<h3>"+name+"</h3>"); 
});

example: http://jsfiddle.net/niklasvh/Wm9M3/

示例:http: //jsfiddle.net/niklasvh/Wm9M3/

PS. you had a syntax error with $("#profile").append("<h3>"+name+"</h3>");as well (you forgot the +around name)

附注。你也有语法错误$("#profile").append("<h3>"+name+"</h3>");(你忘记了+周围name

回答by Naftali aka Neal

You have to use jsonPfor cross domain issues:

您必须jsonP用于跨域问题:

$.get(fburl, function(data){
    console.log(data);
    alert(data.name);
},'jsonp');

Fiddle: http://jsfiddle.net/maniator/34m9J/

小提琴:http: //jsfiddle.net/maniator/34m9J/