2012-07-11 3 views
1

나는 그의 앨범에서 사진을 선택하여 앱의 갤러리에 업로드 할 수있는 옵션을 제공하는 fb 앱을 제작 중입니다.FB API를 사용하여 PHP로 페이스 북 앨범에서 사진을 얻는 방법

그러나 사용자가 드롭 다운 목록에서 앨범 중 하나를 선택하고 양식을 제출하면 스크립트에서 페이지를 다시로드하지 않고 div를 새로 고침합니다.

내가 사용한 해결책은 Ajax를 사용하는 것입니다. 다음의 index.php의 코드는 다음과 같습니다

 <?php 

    session_start(); 
    header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); 
    include 'facebook.php'; 


    $facebook = new Facebook(array(
     'appId' => 'YOUR_APP_ID', 
     'secret' => 'YOUR_SECRET_CODE' 

    )); 


    if(!$_REQUEST['access_token']) 
    $access_token = $facebook->getAccessToken(); 
    else 
    $access_token = $_REQUEST['access_token']; 

    ?> 
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <html xmlns:fb="http://ogp.me/ns/fb#" lang="en" > 
     <head> 
     <meta charset="utf-8" /> 
     <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes" /> 
     <title>MY FACEBOOK APPLICATION</title> 
     <?php require('inc.head.php'); ?> 

     </head> 
     <body> 
     <script> 


    function showAlbum(album_id) 
    { 
    document.getElementById("txtHint").innerHTML = "<br><img src='images/ajax-loader.gif' /><br/><br/>Loading photos..."; 

    if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
     document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
     } 
    } 
    xmlhttp.open("GET","fetch_data.php?album_id="+album_id+"&access_token=<?=$access_token?>",true); 
    xmlhttp.send(); 
    } 
    </script> 
    <? 
     $albums = $facebook->api('/me/albums'); 
     echo '<div class="alb">'; 

     echo " <form name='frm'> 
     <select name='album_id' onchange=\"showAlbum(this.value)\"> 
     <option type='hidden' value=0>Select an album</option>"; 
     foreach($albums['data'] as $album) 
      echo "<option type='hidden' value='".$album['id']."'> ".$album['name']."</option>"; 

     echo '</select></form></div>'; 
     ?> 
      <div id="txtHint" ></div> 
     </body> 
    </html> 

아약스 스크립트는 문제는 내가 처음 앨범을 선택할 때 모든 관련 이미지를 가져 오지 않는다는 것입니다 fetch_data.php

 <?php 
     require_once 'facebook.php'; 


     $facebook = new Facebook(array(
     'appId' => 'YOUR_APP_ID', 
     'secret' => 'YOUR_SECRET_CODE' 

    )); 

     $access_token = $_REQUEST['access_token']; 



       $album_id = $_REQUEST['album_id']; 

       $photos = ''; 
       $photos = $facebook->api("/{$album_id}/photos", array("access_token" => "$access_token")); 

      echo "<div class='slideshow'>"; 

       $photo = ''; 
       foreach($photos['data'] as $photo) 
       { 
        echo "<br /><a href='index.php?src={$photo['source']}&access_token=$access_token'><img title='CLICK PHOTO TO SELECT' src='{$photo['source']}' width=320 border=0/></a><br /><br />"; 
       } 

      echo " </div>"; 
       ?> 

호출합니다. 그러나 다른 앨범을 선택하면 OAuthException이 throw됩니다. 현재 액세스 토큰을 사용하여 현재 사용자에 대한 정보를 쿼리해야합니다. fetch_data.php에서 $ facebook 객체를 새로 작성하면이 문제가 발생합니다.

아이디어가 있으십니까?

+0

: 여기

는 새로운 index.php를 무엇입니까? –

+0

mmmm 질문을하고 자신에게 대답해야한다고 생각합니다. 아마도 Meta에있는 사람들과 확인하십시오. –

답변

4

해결책은 다른 $ facebook 개체를 만들지 않기 위해 json을 사용하는 것이 었습니다 (2 개의 IE 픽스가 필요했지만 아래 주석 참조). 문제는 정확히 무엇을

include 'facebook.php'; 

$facebook = new Facebook(array(
    'appId' => 'YOUR_APP_ID', 
    'secret' => 'YOUR_SECRET_CODE', 
)); 

    //get token 
    $access_token = $facebook->getAccessToken(); 

//don't forget to include the js libraries for jquery and json 
//I am omitting those to save space 

//now get albums 
    $albums = $facebook->api('/me/albums'); 

    //create a drop down list for the user to select one of his albums 

     echo " <form name='frm'> 
     <select name='album_id' onchange=\"showAlbum(this.value)\"> 
     <option type='hidden' value=0>Select an album</option>"; 
     foreach($albums['data'] as $album) 
     echo "<option type='hidden' value='".$album['id']."'> ".$album['name']."</option>"; 

     echo '</select></form>'; 
     ?> 
     <!--this is the div to display the photos of the album selected--> 
      <div id="txtHint" > </div> 

    <!--and now the js--> 
     <script> 
     function showAlbum(album_id) 
    { 
     //until it loads the photos show a loading gif 
     document.getElementById("txtHint").innerHTML = "<br><img src='images/ajax-loader.gif' /><br/><br/>Loading photos..."; 


    //here is the IE fix 
    $.support.cors = true; 

    // get images - the addition of the callback parameter is the 2nd IE fix 
    $.getJSON('https://graph.facebook.com/' + album_id + '/photos?access_token=<?=$access_token?>&callback=?', function(json, status, xhr) { 
     var imgs = json.data; 

     var images=''; 
     for (var i = 0; i < imgs.length; i++) { 
     //each image has a variety of different dimensions 
     //i am selecting the first dimension i.e. [0] and set my own width 
     images +='<br /><img src="' + imgs[i]['images'][0]['source'] + '" width=320><br><br>'; 
     } 
     //append all the photos found for this album id inside the div 
     document.getElementById("txtHint").innerHTML = images; 

     }).error(function(jqXHR, textStatus, errorThrown) { alert(errorThrown); }); 

    } 
</script> 
+0

감사합니다, Alex :) –

+1

HTML에서 작은 따옴표와 큰 따옴표를 혼용하지 마십시오. 코드. 일관성있게하십시오. – Raptor

관련 문제