Ajax学习

来源:互联网 发布:中缅翻译软件 编辑:程序博客网 时间:2024/04/30 00:54
Ajax--Asynchronous Javascript And Xml
局部刷新页面、不能后退
Ajax最早是被Google采用的
最常用的的案例:百度地图
Ajax 中最重要的一个对象是XMLHttpRequest
使用Ajax准备向服务器端发送请求:

xmlHttpRequest.open("GET", "AjaxServlet", true);

这是我们的前台页面:

<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript">
var xmlHttpRequest = null;
function display() {
if (window.ActiveXObject) {
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttpRequest = new XMLHttpRequest();
}
if (null != xmlHttpRequest) {
xmlHttpRequest.open("GET", "AjaxServlet", true);
xmlHttpRequest.onreadystatechange = callBack;
xmlHttpRequest.send(null);
}
}
function callBack() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
var responseText = xmlHttpRequest.responseText;
document.getElementById("div1").innerHTML = responseText;
}
}
}
</script>

</head>


<body>
<input type="button" value="获取文字" onclick="display();" />
<br>
<div id="div1"></div>
</body>
</html>


后台的servlet,向前台打印一个Hello,World:

package com.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class AjaxServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
System.out.println("doGet invoked!");
out.print("hello,World!");
out.flush();
}
}