当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - JSON from facebook graph api returning too slowly

问题描述:

I am playing around with the Facebook graph api at the moment. I am getting all the users friends profile pics and other data and placing them on a google map as a marker.

It is working but it seems to wait for all the data and images to be returned before it starts showing up. Sorry if this is too vauge, I am a beginer. I have tried breaking up the JSON calls into several callback functions but this hasn't helped. I want each friends image to be placed as soon as the data is received.

My code is below (4 calls to get the JSON using jquery ). First call gets the friend list, then for each friend get the image and data and then location data.

$.getJSON("https://graph.facebook.com/" + userid + "/friends?access_token=" + token, function(data) {

$.each(data.data, function(key, val) {

$.getJSON("https://graph.facebook.com/"+ val.id + "?fields=picture", function(idata) {

var img = new Image();

img.src = idata.picture;

$.getJSON("https://graph.facebook.com/"+ val.id + "?access_token=" + token, function(fdata) {

$.getJSON("https://graph.facebook.com/"+ fdata.location.id + "?access_token=" + token , function(ldata) {

$('#map_canvas').gmap('addMarker', {

'id': 'mark',

'position': ldata.location.latitude + ',' + ldata.location.longitude,

'draggable': false,

'bounds': false,

'icon' : image.src,

'title' : fdata.name,

'animation': google.maps.Animation.DROP,

}).click(function() {

$('#map_canvas').gmap('openInfoWindow', {'content': 'Name: ' + fdata.name + '</br>Location: ' + fdata.location.name }, this);

});

});

});

});

});

});

网友答案:

The reason it's slow is you're making lots of queries: One to get your friendlist, then 3 more for each friend to get their picture, ? and location. Each of these API calls takes time. Lots of time.

First, cut down the number of queries. Using the Graph API, you can get everything you need in two:

"https://graph.facebook.com/me/friends?fields=id,name,picture,location&access_token=" + token

Then loop through the results of this query and extract all the location.id values, say into an array called loc. Now run this query:

"https://graph.facebook.com/?fields=location&ids=" + loc.join() + "&access_token=" + token

Now you can loop through the first result to get the names, picture and location id, them loop through the second result to get the location's latitude and longitude.

分享给朋友:
您可能感兴趣的文章:
随机阅读: