使用javascript搜索facebook页面

时间:2013-08-02 05:05:34

标签: javascript facebook-graph-api facebook-javascript-sdk

我有一个HTML应用程序,可以使用纯JavaScript搜索Facebook页面,没有其他库,也没有后端。大多数处理搜索和阅读“页面”的API都不需要用户授权,并且它们支持JSONP(通过“回调”参数)。

我的HTML代码,index.html

<!doctype html>
<head>
  <title>FaceBook Page Search API</title>
  <script type="text/javascript" src='js/app.js'></script>
  <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
  <div class="container">
    <div class="form-search">
      <h3>Search FaceBook Pages</h3>
      <p class="form-search-row"><input id="searchPages" type="text" placeholder="Enter name">
     <button class="btn btn-medium btn-success" onclick="getData()" type="submit">Search</button>
     </p>
   </div>
  </div>
  <div class="offset1 pull-center page-results">
  </div>
 </body>
</html>

和app.js,

var getData = function(){
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
var str, queryInput = document.getElementById("searchPages");
var searchFormRow = document.getElementsByClassName('form-search-row')[0];
var image=document.createElement('img');

if(!queryInput.value){
    return;
}

str = encodeURIComponent(queryInput.value);
image.setAttribute('src', 'img/ajax-loader.gif');
image.setAttribute('width', '30px');
searchFormRow.appendChild(image);

var url = "https://graph.facebook.com/search?type=page&q="+ str;
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
    var done = 4, ok = 200;
    if (http_request.readyState == done && http_request.status == ok) {
        my_JSON_object = JSON.parse(http_request.responseText);
        displayResults(my_JSON_object);
        image.parentNode.removeChild(image);
    }
};
http_request.send(null);
};


var displayResults = function(pages){
   var resultDiv = document.getElementsByClassName('page-results')[0];
   if(pages.data.length){
      resultDiv.innerHTML = "";
   }
   else{
      resultDiv.innerHTML = "No results found";
   }
   for(var i=0; i<pages.data.length; i++)
   {
      var name = pages.data[i].name, category = pages.data[i].category, id= pages.data[i].id;
      var page = document.createElement("div");
      var pname = document.createElement("p");
      var findmore = document.createElement("a");
      var pcategory = document.createElement("p");
      pname.innerHTML = name;
      findmore.innerHTML = " find out more";
      findmore.href= "detail.html?id="+id;
      findmore.target = "_blank";
      pname.appendChild(findmore);
      pcategory.innerHTML = "Category: " + category;
      pcategory.setAttribute('class',"small-font");
      page.setAttribute('class','span2 pageDiv');
      page.appendChild(pname);
      page.appendChild(pcategory);
      resultDiv.appendChild(page);
      console.log(pages.data[i].name);
     }
    };


   var getPageDeatil = function(){
   var query = window.location.search.substring(1);
   var vars = query.split("=");
   getDetailsAjax(vars[1]);
 };

 var getDetailsAjax = function(pageId){
 var my_JSON_object = {};
 var http_request = new XMLHttpRequest();
 var str = encodeURIComponent(pageId);

 var url = "https://graph.facebook.com/"+ str;
 http_request.open("GET", url, true);
 http_request.onreadystatechange = function () {
    var done = 4, ok = 200;
    if (http_request.readyState == done && http_request.status == ok) {
        my_JSON_object = JSON.parse(http_request.responseText);
        displayDetailsResult(my_JSON_object);
    }
 };
 http_request.send(null);
};

var displayDetailsResult = function(detail){
  var resultDiv = document.getElementById('details');
  var displayImage;
  for (key in detail) {
    if (detail.hasOwnProperty(key)) {
        if(key=="cover"){
            displayImage =true;
        }
        else{
            var li = document.createElement("li");
            li.setAttribute('class',"removeDecor");
            li.innerHTML = key+ " : " + detail[key];
            resultDiv.appendChild(li);
        }
    }
   }
   if(displayImage){
    var heading = document.getElementById('header');
    var image =  document.createElement('img');
    image.setAttribute('src', detail.cover.source);
    heading.insertBefore(image);
   }
  };

最后,detail.html

<!doctype html>
<head>
  <title>FaceBook Page Search API - Detail Page</title>
  <script type="text/javascript" src='js/app.js'></script>
  <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body onload="getPageDeatil()">
  <div class="container">
    <h3 id="header">More about Page</h3>
    <div class="well">
      <ul id="details">
      </ul>
    </div>
  </div>
 </body>
</html>

但它在控制台中出现以下错误。

{
  "error": {
     "message": "(#200) Must have a valid access_token to access this endpoint",
     "type": "OAuthException",
     "code": 200
  }
}

页面搜索API不需要授权吗?那怎么解决这个问题呢?

1 个答案:

答案 0 :(得分:2)

谢谢大家,最后通过推荐Facebook开发人员文档解决了我的问题。

首先,在此处获取有关access_token的详细信息,https://developers.facebook.com/docs/reference/api/search/#access_tokens

跨页面和地点对象搜索需要应用访问令牌。

每个应用程序都应在https://developers.facebook.com/apps中注册,以获取app_id和secret_id。

获得此详细信息后, 使用此网址https://graph.facebook.com/oauth/access_token?client_id=app_id&client_secret=secret_id&grant_type=client_credentials

生成access_token

app_id和secret_id应该使用生成的更改。

并在app.js文件中更改了我的请求网址,

var access_token = ""; // my access token here
var url = "https://graph.facebook.com/search?type=page&q="+ str +"&access_token="+access_token;