我正在构建一个 fb 应用程序,它为用户提供从相册中选择照片的选项,以便将其上传到应用程序的图库。
但是,当用户从下拉列表中选择他的一张专辑并提交表单时,我不希望脚本重新加载页面,而只是刷新一个 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>
ajax 脚本调用 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:必须使用活动访问令牌来查询有关当前用户的信息。似乎在 fetch_data.php 中创建一个新的 $facebook 对象会导致这种情况。
有任何想法吗?