我有一个 jquery ajax 函数,它将表单数据提交到一个 php 文件,在该文件中检查数据库并返回响应。但是我的成功函数没有被执行,而是通过错误函数返回响应。
以下是我的 login.js 代码:
$(document).ready(function(){
$("form#loginForm").submit(function() { // loginForm is submitted
var username = $('#username').attr('value'); // get username
var password = $('#password').attr('value'); // get password
if (username && password) { // values are not empty
$.ajax({
type: "POST",
url: "url", // URL of the Php script
contentType: "application/json; charset=utf-8",
dataType: "json", //expected from server in response
// send username and password to the Php script
data: "username=" + username + "&password=" + password,
error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
+ ", textStatus: " + textStatus
+ ", errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
},
success: function(data){ //script was successful, data contains response from mysql database
if (data.error) { // login was not successful
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
$('form#loginForm').hide();
$('div#loginResult').text("data.success: " + data.success);
$('div#loginResult').addClass("success");
} //else
} // success
}); // ajax
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});
这是我的 Login.php 代码:
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$dbhost = '*****';
$dbuser = '*****';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass); // connect to server
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected to database successfully,';
mysql_select_db('sl493',$conn); //pick sl493 database
$result = mysql_query("SELECT *
FROM metauser
WHERE metauser.username = '$username'
AND metauser.password = '$password'") or die(mysql_error()); //select data from metauser table
$row = mysql_fetch_assoc($result);
if($row['username'] == $username) //If username and password not accepted
{$result = 'true login';
$arr = array('success' => "login is successful");
echo json_encode($arr);}
else //if username and password are not accepted
{$result = 'login failed';
$arr = array('error' => "username or password is wrong");
echo json_encode($arr);}
?>
现在,无论我输入正确还是错误的凭据,我都会收到以下响应:
responseText: 连接数据库成功,{"success":"登录成功"} , textStatus: parsererror, errorThrown: Invalid JSON: 连接数据库成功,{"success":"登录成功"} http://i. imgur.com/n1nZ2ac.jpg
它返回“已成功连接到数据库”,这意味着它成功进入 login.php,但它也返回 responseText,它是 ajax:error 的一部分,因为函数执行成功,它不应该出现在哪里。HALP?