Я ценю любую помощь. Я новичок с небольшим опытом работы с jQuery / AJAX, и я сходил с ума, пытаясь понять, почему я не могу понять это.
Я пишу приложение на странице Facebook, у которого есть разрешение пользователя, и загружаю видео на страницу. Все это работает отлично и денди. Это не столько проблема, связанная с API Facebook, сколько проблема с ajax (по крайней мере, я так думаю).
По сути, я пытаюсь получить контроль над страницей НЕКОТОРЫМ способом после того, как пользователь загрузит видео. Я использую [malsup jQuery Form Plugin] [1] для загрузки полученной страницы (которая представляет собой страницу в Facebook с возвращаемыми значениями JSON) в скрытом фрейме.
Я могу запустить ajaxStart, и я проверил это, заставив его изменить цвет фона или напечатать сообщение с предупреждением, когда я нажимаю «Загрузить». Однако, когда загрузка завершена (и она успешно завершена), НИЧЕГО НЕ ПРОИЗОЙДЕТ. Возвращенные значения JSON загружаются в скрытый iframe, и страница находится там. Я пытался заставить ajaxComplete, ajaxStop и ajaxSuccess сработать, но ни один из них не сделал по какой-либо причине.
Итак, вот что я пытаюсь сделать:
- Я хочу перенаправить пользователя или сделать скрытый контент доступным после завершения загрузки файла. Мне даже все равно, есть ли ошибки. Мне просто нужно ЧТО-ТО, чтобы это произошло.
- Я использую плагин jQuery Form, потому что я, к сожалению, недостаточно продвинут, чтобы понять, как использовать это значение и что-то с ним делать, но если кто-то может направить меня в правильном направлении, это будет оценено.
И, наконец, вот мой код:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
iframeTarget: '#output2',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
// bind form using 'ajaxForm'
$('#theform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
</script>
<script type="text/javascript">
jQuery().ready(function(){
$('body').ajaxStart(function() {
$(this).css("background-color","red");
});
$('body').ajaxSend(function() {
$(this).css("background-color","blue");
});
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
$('body').ajaxStop(function() {
$(this).css("background-color","purple");
});
});
</script>
</head>
<body>
<?php
$app_id = "xxxxxxx";
$app_secret = "xxxxx";
$my_url = "xxxxxx";
$video_title = "xxxxxxxxx";
$video_desc = "xxxxxxxxx";
$page_id = "xxxxxxxx";
$code = $_REQUEST["code"];
if(empty($code)) {
// Get permission from the user to publish to their page.
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&display=popup&scope=email,publish_stream,manage_pages";
$current_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($current_url != $dialog_url)
{
echo('<script>window.location ="' . $dialog_url . '";</script>');
}
} else {
// Get access token for the user, so we can GET /me/accounts
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
$accounts_url = "https://graph.facebook.com/me/accounts?" . $access_token;
$response = file_get_contents($accounts_url);
// Parse the return value and get the array of accounts we have
// access to. This is returned in the data[] array.
$resp_obj = json_decode($response,true);
$accounts = $resp_obj['data'];
// Find the access token for the page to which we want to post the video.
foreach($accounts as $account) {
if($account['id'] == $page_id) {
$access_token = $account['access_token'];
break;
}
}
// Using the page access token from above, create the POST action
// that our form will use to upload the video.
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&access_token=". $access_token;
// Create a simple form
echo '<form action=" '.$post_url.' " method="POST" enctype="multipart/form-data" id="theform">';
echo 'Please choose a file:';
echo '<input name="file" type="file">';
echo '<input type="submit" value="Upload" id="button-upload" />';
echo '</form>';
}
?>
<iframe id="output2" name="output2"></iframe>
</body></html>
Спасибо за вашу помощь !!