1、启动运行效果
2、代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<script>
function login() {
//获取用户名与密码
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
//声明请求对象
var xmlhttp;
//实例化请求对象
if (window.XMLHttpRequest){
//IE7+,Firefox.Chrome,Opera,Safari浏览器里执行代码
xmlhttp = new XMLHttpRequest();
}else {
//IE5,6 浏览器执行代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//监听请求状态变化,一旦有变化,执行相应的回调函数
xmlhttp.onreadystatechange = function () {
//判断请求是否成功,响应是否完成
if (xmlhttp.status == 200 && xmlhttp.readyState == 4){
//根据返回值不同跳转不同页面
if (xmlhttp.responseText == "success"){
//跳转到登录成功页面,传递用户名
window.location = "success.html?username=" + username;
}else {
//跳转到登录失败页面,传递用户名
window.location = "failure.html?username=" + username;
}
}
}
//新建HTTP请求,采用get方式,请求采用 异步方式
xmlhttp.open("POST","/AjaxDemo/login",true);
//设置请求
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//定义要传递的数据
var data = "username=" + encodeURIComponent(username) +"&password=" + encodeURIComponent(password);
//发送HTTP请求,传递参数
xmlhttp.send(data);
}
function reset() {
//清空用户名与密码数据
document.getElementById("username").value="";
document.getElementById("password").value="";
}
</script>
</head>
<body>
<h3 style="text-align: center">用户登录</h3>
<form>
<table border="1" cellpadding="10" style="margin: 0px auto">
<tr>
<td align="center">用户名</td>
<td><input type="text" id="username" name="username"/></td>
</tr>
<tr>
<td align="center">密码</td>
<td><input type="password" id="password" name="password"/></td>
</tr>
<tr align="center">
<td colspan="2">
<button type="button" onclick="login()">登录</button>
<button type="button" onclick="reset()">重置</button>
</td>
</tr>
</table>
</form>
</body>
</html>
来源:CSDN
作者:仙女 吧啦啦能量
链接:https://blog.csdn.net/yingjiaxin/article/details/103235384