总提示:
POST http://localhost/app/Home/View/Login/%7B:U(%22Login/checkLogin%22)%7D 403 (Forbidden)
index.html 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax登陆演示</title>
<script src="http://cdn.bootcss.com/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<<fieldset>
<legend>登陆演示表单</legend>
<input type="text" name="uname" id="uname"><br>
<input type="password" name="upwd" id="upwd"><br>
<input type="submit" value="登陆" id="checkLogin">
</fieldset>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#checkLogin').click(function(){
var $unameVal = $.trim($('#uname').val());
var $upwdVal = $.trim($('#upwd').val());
//如果没有填写数据,则直接返回false.不执行ajax提交操作
/*if($unameVal == '' || $upwdVal == ''){
alert('请输入用户名和密码');
return false;
} */
/*
$.post(url,parameters,callback);
url : post提交的服务器端资源地址。
parameters: 需要传递到服务器端的参数。 参数形式为“键/值”。
callback : 在请求完成时被调用,这里我们通过$data来接收服务器返回的数据
*/
$.post('{:U("Login/checkLogin")}', {uname : $unameVal,upwd : $upwdVal},function($data) {
alert($data.info);
if($data.status == 1){
location.href = $data.url;
}else{
$('#uname').reset();
$('#upwd').reset();
}
});
});
});
</script>
LoginController.class.php 页面
<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends Controller{
public function index(){
$this->display();
}
public function checkLogin($uname,$upwd){
$data = array();
if(!empty($uname) && !empty($upwd)){
//1.这里的业务逻辑,小伙伴们自由发挥.我呢就简单的处理一下.只要接收到数据不为空,就表示成功.
//2.如果你觉得拼装数组比较麻烦,那么你可以将$this->success()或者$this->error中的第三个参数定义为true,即可返回json数据.例如:$this->success('登陆成功',U('User/index'),true).
//3.我个人倾向于拼装数组,主要原因是自己拼装的数组数据结构比较明了,方便阅读.
$data['status'] = 1;
$data['info'] = '登陆成功';
$data['url'] = U('User/index');
}else{
$data['status'] = 0;
$data['info'] = '用户名和密码不能为空';
$data['url'] = U('Login/index');
}
//通过ajaxReturn()方法返回我们之前生成的数组
$this->ajaxReturn($data);
}
}
/*
* @param $uname string 接收到的用户名
* @param $upwd string 接收到的密码
* @return $data array 验证结果
* @author uctoo<uctoo@foxmail.com>
*/