我有一个小问题,也许因为我是ajax编程的初学者,我在ajax jquery中创建了一个调用php文件的函数,该函数向数据库发出有关玩家信息的请求。当 php 文件回复 ajax 函数时,我得到一个带有 null 值的对象作为答案。
我的代码中是否遗漏了一行?或者我忘了做什么?
这是我的代码, AJAX功能:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
以及 php 文件:
<?php
include("connexion_bdd.php");
$_GET['mail'] = $mail;
$req = $bdd->prepare('SELECT * FROM joueurs WHERE mail = ?');
$req->execute(array($mail));
$reponse = $req->fetch();
$return = array();
$return["user_name"] = $reponse["nickname"];
$return["profile_pic"] = $reponse["profile_pic"];
$return["user_id"] = $reponse["id"];
print(json_encode($return));
?>
在ajax函数的成功中,我得到了这个:
{"user_name":null,"profile_pic":null,"user_id":null}
虽然数据库不为空。 你认为我的错误在哪里? php 文件或 ajax 函数?或者两者兼而有之?
感谢您的帮助:)
编辑: 我根据传递变量 AJAX->PHP 的方式更改了我的代码。 我已经在数据库上测试了我的 sql 查询,它工作正常,但在将对象从 php 文件传递到 AJAX/JS 文件的 succes 函数后,我仍然遇到空值问题。 关于我的代码有什么问题有什么想法吗?
再次感谢。
最佳答案
这里有两个问题。
首先,您没有在 jQuery AJAX 请求中发送邮件参数。您需要将 GET 参数附加到 url
键下的 URL 末尾:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php?mail=youremail@gmail.com",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
第二个问题是您的 PHP 脚本中的 $mail
变量赋值向后。应该是
$mail = $_GET['mail'];
当您使用 GET 请求调用脚本时,$_GET['mail']
由 PHP 自动设置。但由于您在准备好的 SQL 语句中引用了 $mail
,因此您希望将 $_GET['mail']
的值分配给 $mail
.
关于javascript - AJAX PHP - 响应是一个具有空值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36105649/