我有一个数据库,其中Facebook用户ID, Facebook用户名和邮件地址是写的。当文档加载时,我想检查给定的ID(存储在javascript值中)是否已经存在于数据库中。所以我要做的是用PHP检查我的Javascript变量(值)是否存在于数据库中。有什么办法吗?
可能最简单的方法是向包含该ID的服务器(PHP脚本)发出XHR (AJAX)请求,然后检查服务器上是否存在该ID。
您可以使用ajax。
使用jQuery的例子:
$.post("check.php",{id: your_var},function(data){
alert(data);
});
check.php保存检查数据库的PHP代码。
我认为您需要AJAX。例如:
<script>
//user id
var uid = '100';
//AJAX create
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//GET request create and send
xmlhttp.open("GET","checkuser.php?uid="+uid,false);
xmlhttp.send();
//Good. in "xmlhttp.responseText" will store true or false (user exist or not)
alert(xmlhttp.responseText); //check answer from PHP
</script>
Ok。现在PHP脚本。
//这是checkuser.php
<?php
$uid = int()$_GET['uid'];
echo (bool)functionForCheckIdInDB($uid);
?>
注。当然使用jQuery会更容易。