一个完整的Ajax提交(POST)
前台(JqueryAjax)
$(function(){ $('.dl_btn').click(function(){ $.ajax({ type: "POST", // 提交方式 POST dataType : "json", // 预期服务器返回的数据类型 json data: $("#login").serialize(), // 将表单中要提交的内容序列号 async : true, // 默认设置下,所有请求均为异步请求 url : "__GROUP__/Public/checkLogin", // 需要提交的URL success : function(msg){ // 请求成功后的回调函数。 // console.debug(msg); if(dmsg.code !=8){ alert(msg.message); }else{ window.location.href='/Index/index/'; } } }, // XHR: 全称: XMLHttpRequest error:functuon(jqXHR){ alert("错误信息为" + "jqXHR.status"); } // 另一种写法 error: function (data, status, e) {//服务器响应失败处理函数 alert(e); } }); }) });
注意,如果将ajax提交封装到一个方法中,同步方式必须选择false!
2. 后台处理(PHP):
/** * 检测登录 */ public function checkLogin() { if($_SESSION['userInfo']){ $this->redirect('/'); } // 初始化output $output['code'] = 0; if(empty($_POST['username'])){ $output['code'] = 5; $output['message'] = '用户名不能为空'; $this->ajaxReturn($output,'json'); } if(empty($_POST['password'])){ $output['code'] = 6; $output['message'] = '密码不能为空'; $this->ajaxReturn($output,'json'); } if(empty($_POST['verify'])){ $output['code'] = 7; $output['message'] = '验证码不能为空'; $this->ajaxReturn($output,'json'); } $data = array( 'user_account' => $_POST['username'], 'user_pwd' => $_POST['password'], 'verify' => $_POST['verify'] ); $user = new UserModel(); $userInfo = $user->getUserByAccount($data['user_account']); if($_SESSION['verify'] != md5($data['verify'])){ $output['code'] = 4; $output['message'] = '验证码不正确,请重新输入'; $this->ajaxReturn($output,'json'); } if($userInfo){ if(!$userInfo['user_status']){ $output['code'] = 2; $output['message'] = '用户已冻结,禁止登录'; $this->ajaxReturn($output,'json'); } if($userInfo['user_pwd'] == md5($data['user_pwd'])){ $_SESSION['userInfo'] = $userInfo; $node = new UserNodeModel(); $_SESSION['node'] = $node->getUserNodeById($userInfo['id']); $output['code'] = 8; $this->ajaxReturn($output,'json'); }else{ $output['code'] = 3; $output['message'] = '密码不正确,请重新输入'; } }else{ $output = array( 'code' => 1, 'message' => '用户不存在' ); }
服务器返回数据:
ThinkPHP: $this->ajaxReturn($output, 'json');
http://doc.thinkphp.cn/manual/ajax_return.html
原生: echo json_encode($array)