Ajax出道已经不久了,决定一试身手,首先要了解Ajax的原理
Ajax并不是什么新技术,它集中了集中技术:
1. HTML 用于建立 Web 表单并确定应用程序其他部分使用的字段。
2.JavaScript 代码是运行 Ajax 应用程序的核心代码,帮助改进与服务器应用程序的通信。
3.DHTML 或 Dynamic HTML,用于动态更新表单。我们将使用 div、span 和其他动态 HTML 元素来标记 HTML。
4.文档对象模型 DOM 用于(通过 JavaScript 代码)处理 HTML 结构和(某些情况下)服务器返回的 XML。
首先了解XMLHttpRequest对象,这是一个javascirpt对象,通过XMLHttpRequest与服务器通话,这是ajax的强大技术。创建方式:
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
其次,Ajax的请求与响应。
发出请求:
1.从 Web 表单中获取需要的数据。
2.建立要连接的 URL。
3.打开到服务器的连接。
4.设置服务器在完成后要运行的函数。
5.发送请求。
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "server/svrList.jsp", true);
xmlHttp.send(null);
xmlHttp的属性onreadystatechange可以告诉服务器在运行完成之后,由谁来做什么。这里由handleStateChange来处理。
function handleStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert('the server replied with ' + xmlHttp.responseText);
}
else{
alert('wrong');
}
}
}
xmlHttp的open方法有三个参数:
第一个告诉服务器请求的方式是GET、POST
第二个告诉服务器请求的URL,它可以是servlet、jsp或者是struts的action(本质也是servlet)
第三个“true”是表示是一个异步请求,false则表示同步。
send方法的参数要设置为null,当open的设置成异步请求时。
最后处理响应:
function handleStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert('the server replied with ' + xmlHttp.responseText);
}
else{
alert('wrong');
}
}
}
通过xmlHttp的属性readyState来判断状态。
0 uninitialized
1 loading
2 loaded
3 interactive
4 complete 完毕
status属性表示返回状态。
404 表示没找到
200 表示ok
responseText以字符串形式返回
responseXML以xml形式返回,可以W3C的DOM进行解析。
完整的例子:
<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<%@ taglib uri="WEB-INF/tlds/site-utils.tld" prefix="site-utils" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function startRequest(){
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "server/svrList.jsp", true);
xmlHttp.send(null);
}
function handleStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert('the server replied with ' + xmlHttp.responseText);
}
else{
alert('wrong');
}
}
}
</script>
</head>
<body>
hello:
<site-utils:lastModified/>
<form action="#">
<input type="button" value="ajax test" onclick="startRequest()"/>
</form>
</body>
</html>
完