PHP怎么使用AJAX返回登录成功信息!
本文介绍了PHP怎么使用AJAX返回登录成功信息!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
就是说,当我点击提交表单的按钮时,用ajax来发送请求,然后后台怎么返回登录成功或者登录失败的信息给前台页面去展示,整个过程是无刷新的!!求各位大神给点思路!!!
解决方案
以下是完整参考代码,index.php为登录页面,ajax.php为处理ajax无刷新请求页面。
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>登录</title>
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
帐号:<input type="text" id="account" />
<br><br>
密码:<input type="password" id="password" />
<br />
<input type="button" value="登录" id="btnlogin" />
<script type="text/javascript">
$(function(){
$("#btnlogin").click(function(){
$.ajax({
type:"post",
url:"ajax.php",
data:{account:$("#account").val(),password:$("#password").val()},
dataType:"json",
success:function(data){
if(data.type==1){
alert("登录成功");
}else{
alert("登录失败");
}
},
error:function(){
alert("请求异常");
}
});
});
});
</script>
</body>
</html>
ajax.php
<?php
header("Content-Type:text/html; charset=utf-8");
$account = $_POST['account'];
$password = $_POST['password'];
$result = array();
if ($account != '' && $password != '') {
//$row = $db->query("SELECT * FROM account where user = '".$account."' and password = '".$password."'");
$row = true;//这里去查数据库,假设这里返回true
if($row){
$result['type'] = 1;
$result['msg'] = '登录成功';
}else{
$result['type'] = 0;
$result['msg'] = '用户名或密码不正确';
}
} else {
$result['type'] = 0;
$result['msg'] = '参数传输不正确';
}
echo json_encode($result);
?>
这篇关于PHP怎么使用AJAX返回登录成功信息!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文