您好我已经创建了一个使用ajax方法登录的脚本我试过但是这对我来说不起作用请你告诉我为什么我无法使用这个
function login() {
var username = document.getElementById('username').value;
var pass = document.getElementById('pass').value;
if(username == '' && pass == '') {
alert('Fields could not be left empty');
} else {
$.ajax({
type : "POST",
url : "includes/register.php",
data : "command=login&username="+username+"&password="+pass,
datatype : "json",
success : function(data) {
if (data.status == 200) {
alert('Successfull');
var return_data = data.responseText;
document.getElementById('messagearea').innerHTML = return_data;
} else {
alert('Unsuccessful');
}
}
});
}
}
它应该运行警报成功,但我得到警报('不成功')这意味着状态不等于200可以任何人帮我解决这个问题
这是我的PHP代码
if(isset($_POST['command']) && $_POST['command'] == 'login') {
$username = $_POST['username'];
$pass = $_POST['pass'];
$password = md5($pass);
$check = mysqli_query($connection, "SELECT * FROM users WHERE username = '$username'");
$result = mysqli_num_rows($check);
if($result != 1) {
echo "<div class='message'>Response Successful</div>";
} else {
echo "<div class='message'>Username/Password did not matched</div>";
}
}
答案 0 :(得分:2)
Applet started
中的 T
应该是资本,
datatype
根据服务器代码,您的数据应该如下所示
$.ajax({
type: "POST",
url: "includes/register.php",
data: "command=login&username=" + username + "&password=" + pass,
dataType: "json",
更改成功处理程序中的代码,如下所示,
data: "command=login&username=" + username + "&pass=" + pass,
答案 1 :(得分:1)
如果要检查xhr请求状态,则应在success : function(data,text,xhr) {
if (xhr.status == 200) {
alert('Successfull');
var return_data = data;
document.getElementById('messagearea').innerHTML = return_data;
} else {
alert('Unsuccessful');
}
}
中使用3参数。
if(isset($_POST['command']) && $_POST['command'] == 'login') {
$username = $_POST['username'];
$pass = $_POST['pass'];
$password = md5($pass);
$check = mysqli_query($connection, "SELECT * FROM users WHERE username = '$username'");
$result = mysqli_num_rows($check);
if($result != 1) {
echo json_encode("<div class='message'>Response Successful</div>");
} else {
echo json_encode("<div class='message'>Username/Password did not matched</div>");
}
}
for dataType:“json”
{{1}}
答案 2 :(得分:0)
您可以尝试此解决方案:
$.ajax({
type: "POST",
url: "includes/register.php",
data: {command: "login", username: username, password: pwd},
dataType: "json",
不要使用&#34;传递&#34;进入脚本jQuery,因为有时候它不能正常工作。
再见! :d
答案 3 :(得分:0)
您需要在ajax成功函数中再添加两个对象,这将有助于您获得有关请求的更多信息。
$.ajax({
type : "POST",
url : "register.php",
data : "command=login&username="+username+"&password="+pass,
datatype : "json",
success : function(data,xhr,req) {
if (req.status == 200) {
alert('Successfull');
var return_data = data.responseText;
document.getElementById('messagearea').innerHTML = return_data;
} else {
alert('Unsuccessful');
}
}
});
此外,您需要将返回数据编码为JSON,以便您的请求返回类型与JSON匹配。如果你通过开发人员工具baar仔细查看你的ajax请求,你会看到还有两个对象返回,你的请求包含不同的东西。