使用 ajax 获取表单以获取 php 响应时遇到问题。javascript 似乎是正确的,因为如果我删除 login_ajax.php 上的所有内容并且只使用以下内容,它就可以工作
echo 'CORRECT'
//or
echo 'INCORRECT'
一旦我使用了真正的 php 代码,ajax 就不会得到 PHP 的任何响应。更奇怪的是,如果我删除
return false
从 javascript 然后提交表单,我确实看到浏览器的 login_ajax.php 上显示了正确或错误。
HTML:
<form id="login" action='login_ajax.php' method="get">
<label>Email: <input type="text" name="email" id="email" value="nano@nano.com"></label>
<label>Password: <input type="text" name="password" id="password" value="x"></label>
<input type="submit" value="login">
<div id="straight_response">php response here</div>
<div id="message">status</div>
</form>
PHP:
if (isset($_GET['password'])) {
$email = $_GET['email'];
$password = $_GET['password'];
$stored_pass = "123";
if ($password == $stored_pass) {
echo "CORRECT";
} else {
echo "INCORRECT";
}
}
//Javascript works when using one of the two lines below instead of the code above
//echo 'INCORRECT';
//echo 'CORRECT'
JAVASCRIPT:
$('#login').submit(function(){
var email;
var password;
email = $('#email').val();
password = $('#password').val();
var data = {};
data.email = email;
data.password = password;
var options = {};
options.dataType = 'text';
options.type = 'get';
options.url= 'login_ajax.php';
options.success = function (response) {
// jQuery.trim(response);
console.log(response.results);
console.log(response.query);
$('#always').text(response);
if (response === 'CORRECT') {
$('#message').text('you got it right');
console.log("good combination");
}
else if (response === 'INCORRECT') {
$('#message').text('sorry, try again');
console.log("bad combination");
}
};
$.ajax(options);
return false;
});//#login function