我是php / ajax / jquery的新手,我遇到了一些问题。我试图将json传递给php文件,使用json数据运行一些任务,然后发回一个响应。我使用facebook api登录用户,获取详细信息,将详细信息转换为json,发送json toe服务器并让服务器检查用户ID是否已存在于数据库中。这是我的javascript / jquery
function checkExisting() {
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.id );
var json = JSON.stringify(response);
console.log(json);
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
}
这是我的php文件
if(isset($_POST['user']) && !empty($_POST['user'])) {
$c = connect();
$json = $_POST['user'];
$obj = json_decode($json, true);
$user_info = $jsonDecoded['id'];
$sql = mysql_query("SELECT * FROM user WHERE {$_GET["id"]}");
$count = mysql_num_rows($sql);
if($count>0){
echo 1;
} else{
echo 0;
}
close($c);
}
function connect(){
$con=mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to Database: " . mysqli_connect_error();
}else{
return $con;
}
}
function close($c){
mysqli_close($con);
}
我希望它返回1或0,具体取决于用户id是否已经在表中,但它只返回了很多html标签。 。 json看起来像这样
{"id":"904186342276664","email":"ferrylefef@yahoo.co.uk","first_name":"Taak","gender":"male","last_name":"Sheeen","link":"https://www.facebook.com/app_scoped_user_id/904183432276664/","locale":"en_GB","name":"Tadadadn","timezone":1,"updated_time":"2014-06-15T12:52:45+0000","verified":true}
答案 0 :(得分:0)
修复查询部分:
$sql = mysql_query("SELECT * FROM user WHERE {$_GET['id']}");
或另一种方式:
$sql = mysql_query("SELECT * FROM user WHERE ". $_GET['id']);
然后在你的ajax
中使用dataType
总是更好
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
dataType: "jsonp", // for cross domains or json for same domain
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
答案 1 :(得分:0)
在PHP中分配$jsonDecoded
的位置?看起来没有分配给我。
我想你想说:
$obj = json_decode($json, true);
$user_info = $obj['id'];
你的SELECT毫无意义。您在POST期间引用$_GET
。也许你想说:
$sql = mysql_query("SELECT * FROM user WHERE id = {$user_info}");