<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
//1.获取a节点,并为其添加onclick响应函数
document.getElementsByTagName("a")[0].onclick = function(){
//2.创建一个 XMLHttpRequest 对象
var request = new XMLHttpRequest();
//3.准备发送请求数据:url
var url = this.href;
//4.调用 XMLHttpRequest 对象的open方法
request.open("GET",url,true);
//5.调用 XMLHttpRequest 对象的send方法
request.send(null);
//6.为 XMLHttpRequest 对象添加 onreadystatechange 响应
request.onreadystatechange = function(){
//7.判断响应是否完成:XMLHttpRequest 对象的 readyState 属性值为4时
if(request.readyState == 4){
//8.在判断响应是否可用:XMLHttpRequest 对象的status 属性值为200
if(request.status == 200){
//9.打印响应结果:responseText
alert(request.responseText);
}
}
}
return false;
}
}
</script>
</head>
<body>
<a href="helloAjax.txt">Hello Ajax</a>
</body>
</html>
结果:
readyState 属性可能的值:
状态 描述
0 请求未初始化(在调用 open() 之前)
1 请求已提出(调用 send() 之前)
2 请求已发送(这里通常可以从响应得到内容头部)
3 请求处理中(响应中通常有部分数据可用,但是服务器还没有完成响应)
4 请求已完成(可以访问服务器响应并使用它)
其它属性如下:
将Ajax内容改成jQuery来写,效果一样,更简单快捷
登陆注册验证Ajax:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="ajax方式">
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function login() {
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/users/login" ,//提交到的地址
data: $('#form1').serialize(),
success: function (result) {
console.log(result);//打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
alert("SUCCESS");
}
;
},
error : function() {
alert("异常!");
}
});
}
</script>
</head>
<body>
<div id="form-div">
<form id="form1" οnsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/></p>
<p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p>
<p><input type="button" value="登录" οnclick="login()"> <input type="reset" value="重置"></p>
</form>
</div>
</body>
</html>