下面的代码是Facebook的"使用JavaScript SDK登录Web",它将浏览器的电子邮件地址和名称发送到客户端javascript。
但是,如何将电子邮件和名称POSted发送到我网站服务器上的PHP文件中,以便我可以使用PHP登录用户?
function statusChangeCallback(response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
document.getElementById('status').innerHTML = 'Please log ' + 'into this app.';
} else {
document.getElementById('status').innerHTML = 'Please log ' + 'into Facebook.';
}
}
function checkLoginState() {
FB.getLoginStatus(function(response){
statusChangeCallback(response);
});
}
function testAPI() {
FB.api('/me', {fields: 'email,name'},function(response) {
document.getElementById('status').innerHTML = 'Thanks for logging in again, ' + JSON.stringify(response) + '!<br/><img src="https://graph.facebook.com/'+response.id+'/picture?width=300" />';
});
}
$(document).ready(function() {
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_US/sdk.js', function(){
FB.init({
appId: '211867502496511',
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse social plugins on this page
version: 'v2.5' // or v2.0, v2.1, v2.2, v2.3
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
});
});
function doalog(){
FB.login(function(response){
statusChangeCallback(response);
});
}
您可以在客户端 JavaScript 中使用手动网络的主力:XMLHttpRequest。
基本上,这是一个允许您手动与服务器通信的对象。您可以将其与 FormData 对象结合使用,以将数据发布到您的服务器。您发送的请求可以像任何其他表单 POST 请求一样处理。
获得电子邮件和姓名后,您可以执行此操作。
var name = theMethodYouUseToGetTheName();
var email = theMethodYouUseToGetTheEmail();
var request = new XMLHttpRequest();
request.onReadyStateChanged = function() {
if (request.readyState == 4) {
if (request.status == 200) {
// your request has been sent and you might have a response
} else {
// there has been an error
}
}
}
var formData = new FormData();
formData.append("name", name);
formData.append("email", email);
request.open("POST", "http://yourwebsite.com/your/php/file.php", true);
request.send(formData);
然后在您的服务器上,您可以像往常一样使用
$userName = $_POST["name"];
$userEmail = $_POST["email"];