Determining if Facebook user likes a specific post - Javascript
I'm developing a facebook application using the javascript sdk that retrieves specific wall posts and allows users to like or unlik开发者_如何转开发e them. To complete this functionality, I need to know whether or not the user likes each post to begin with. What would be the best way to determine this? I thought about retrieving all the likes for a particular post, iterating through the ids and testing each one against the user's id, but that doesn't seem like an efficient solution. Any better ideas? Thanks in advance.
As long as you know the user_id
and the post_id
it's an easy task:
FB.api({
method: 'fql.query',
query: 'SELECT object_id FROM like WHERE post_id="post_id" AND user_id=me()'
},
function(response) {
if(response.length) {
// the user likes the post!
}
}
);
Table used: like
It is possible, you can get it in the form on a json array . then check if your user has liked it or not . I don't think theres other way, but lets wait for experienced users to answer this ;) http://developers.facebook.com/docs/reference/api/post/
Consider using FQL for this matter. You can use the like
(docs) table to retrieve the list of users who liked a post. Having this list you can check whether your user is IN
that list or not.
You retrieve this list just once, and then you check for your id (or ids).
Example in javascript:
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.api({
method: 'fql.query',
query: 'SELECT user_id FROM like WHERE object_id=193397964020317'
},
function(response) {
var results = [];
for (var i = 0; i < response.length; i++) {
results.push(response[i].user_id);
}
if (results.indexOf("725047048") != -1) {
// exists
} else {
// doesnt exists
}
}
);
</script>
I give you an example in PHP too, perhaps someone needs it:
$results = json_decode(file_get_contents("https://api.facebook.com/method/fql.query?query=".urlencode("SELECT user_id FROM like WHERE object_id='193397964020317'")."&format=json"));
if ($results) {
$user_ids = array();
foreach ($results as $result) {
$user_ids[] = $result->user_id;
}
}
var_dump($user_ids);
if (in_array(CURRENT_USER_ID, $user_ids)) {
// exists
} else {
// does not exists
}
Good luck!
精彩评论