我需要知道这个函数的错误在哪里?创建是为了以简单的登录表单验证电子邮件和密码......
function check_login(){
// ID Name of the button used to validate
$("#bt_login").click(function(){
// creating a variable for email and password inputs
var email = $('#email').val();
var password = $('#password').val();
// If input is left blank and you hit login, nothing happens
if(email == "" && password == ""){
}
else{
$.ajax({
type: "POST",
url: "checklogin.php",
data: "email="+ email ,
data: "password="+ password ,
success: function(html){
if(data) {
alert("ok");
}
else {
alert("Wrong email and password");
}
}
})
return false;
}
})
}
当我点击按钮提交表单时,没有任何事情发生!没错!没什么!
我在这里调用函数:
<script type="text/javascript">
doc("bt_login").addEventListener("click", check_login());
</script>
“bt_login”是表单
的提交按钮的名称和ID这是我的checklogin.php
<?php
session_start();
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $_POST['password'];
include('db.php');
//email & pass sent from form
$email = $_POST['email'];
$password = $_POST['password'];
//to protect MySQL injection
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM $tbl_name WHERE email = '$email' and password = '$password'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
//header("location:xxx.html");
//echo "ok";
echo '<script type="text/javascript">alert("Email and Password Exist!"); </script>';
}
else {
//header("location:xxx.html");
//echo "Wrong Username or Password";
echo '<script type="text/javascript">alert("Wrong Email or Password"); </script>';
}
?>
答案 0 :(得分:0)
您正在功能块中创建一个事件处理程序(通过jquery)。调用函数只是注册处理程序。删除功能块和其他addEventListener
行:
$("#bt_login").click(function(){
// creating a variable for email and password inputs
var email = $('#email').val();
var password = $('#password').val();
// If input is left blank and you hit login, nothing happens
if(email == "" && password == ""){
}
else{
$.ajax({
type: "POST",
url: "checklogin.php",
data: {email: email ,password: password },
success: function(response){
if(response.success) {
console.log(response.message);
}
else {
console.log(response.error);
}
},
error: function(error){
console.log(error);
}
})
return false;
}
})
在你的php中你应该发送json数据,而不是脚本标签:
$response = [];
if($count == 1){
$response['success'] = true;
$response['message'] = 'Email and Password Exist';
}
else {
$response['success'] = false;
$response['error'] = 'Wrong Email or Password';
}
//set header and return json
header('Content-Type: application/json');
die(json_encode($response));
您还要定义ajax请求的data属性两次,这是不正确的,并且您的成功回调会收到名为html
的变量,但您会检查data
。
我已将其更改为response
以匹配php中的变量名称 - 这不是必需的,但会使代码更容易理解