1、登录页 form.html
<form>
<input type="text" name="username" placeholder="用户名">
<input type="password" name="pwd" placeholder="密码">
<select name="city"></select>
<button type="button" onclick="dologin()">登录</button>
<button type="button" onclick="dologin1()">登录2</button>
</form>
<script type="text/javascript">
// post (用的最多)
function dologin() {
var _username = $.trim($('input[name="username"]').val());
var _pwd = $.trim($('input[name="pwd"]').val());
// $.post('dologin.php', $('form').serialize(), function(res){
$.post('dologin.php',{username:_username,pwd:_pwd}, function(res){
alert( res.msg );
if(res.code==0){
window.location.href = "home.html";
}
}, 'json');
}
// get
function dologin1() {
var _username = $.trim($('input[name="username"]').val());
var _pwd = $.trim($('input[name="pwd"]').val());
$.get('dologin.php?username='+_username+'&pwd='+_pwd, function(res){
alert( res.msg );
if(res.code==0){
window.location.href = "home.html";
}
}, 'json');
}
// 异步加载数据
function getdata(){
$.get('getcity.php',function(res){
if( res.code==0 ){
var html = '';
$.each( res.data, function(i,v){
html += '<option value="'+v.id+'">'+v.title+'</option>';
});
$('select[name="city"]').html( html ); // $('select[name="city"]').empty().append(html);
}
},'json');
}
getdata();
</script>
2、后台验证 dologin.php
// 方便演示,写了$_REQUEST
$username = $_REQUEST['username']; // $_POST['username'], $_GET['username']
$pwd = $_REQUEST['pwd'];
if($username!='admin'){
$data = json_encode( ['code'=>1,'msg'=>'用户名错误'] );
exit($data);
}
if($pwd!='123'){
$data = json_encode( ['code'=>1,'msg'=>'密码错误'] );
exit($data);
}
$data = json_encode( ['code'=>0,'msg'=>'登录成功'] );
exit($data);
3、获取数据 getcity.php
$citys = [
['id'=>3,'title'=>'南京'],
['id'=>6,'title'=>'无锡'],
['id'=>7,'title'=>'镇江']
];
$data = json_encode( ['code'=>0, 'msg'=>'success', 'data'=>$citys] );
exit($data);
4、首页 home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>系统首页</title>
</head>
<body>
系统首页
</body>
</html>