1. use 'button' for login instead of 'form' type
<button id="register">login</button>
2. create the Jquery mehtod for post login
$(document).ready(function () {
//alert ("am here");
$('#register').click(function () {
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: '/practice/index.php/Home/Login/validate',
type: 'post',
data: {
username: username,
password: password
},
async: false,
error: function () {
alert('error');
},
success: function (data) {
switch (data) {
case '0':
alert("going to redirect");
document.location= "www.baidu.com";
break;
case '1':
// $('#hehe').html('username not exist');
alert("用户名不存在");
break;
case '2':
// $('#hehe').html('password wrong');
alert("密码错误,请重新输入");
break;
}
}
});
});
});
3. TP code
public function validate()
{
// var_dump($_POST['username']);die();
$user = M('User');
$post_array['username'] = isset($_POST['username']) && trim($_POST['username']) ? $_POST['username'] : 0;
$post_array['password'] = isset($_POST['password']) && trim($_POST['password']) ? $_POST['password'] : 0;
$map['username'] = $_POST['username'];
$result = $user->where($map)
->field('username,password')
->select();
// var_dump($result[0]['password']);die();
if ($result == null) {
echo 1;
} else {
if ($result[0]['password'] != $_POST['password']) {
echo 2;
} else {
// $this->redirect('__ROOT__/index.php/Home/Homepage/index');
echo 0;
// go to home page;
}
}
}