AJAX与java servlet结合使用的异步传输实例。html页面代码(使用了jquery):
-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
//定义一个全局的XmlHttpRequest类型的变量
var xmlHttp = false;
//创造一个XmlHttpRequest对象
function createXmlHttpRequest() {
/* Create a new XMLHttpRequest object to talk to the Web server */
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e2) {
xmlHttp = false;
}
}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != ‘undefined’) {
xmlHttp = new XMLHttpRequest();
}
}
//发送异步请求
function callServer() {
createXmlHttpRequest();
var str = $(“#t1″).val();
var url = “test1.do”;
// Open a connection to the server
xmlHttp.open(“POST”, url, true);
// Setup a function for the server to run when it’s done
xmlHttp.onreadystatechange = updatePage;
//使用post方法提交是,这句非常重要,否则servlet无法接收参数
xmlHttp.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
// Send the request
var param = “a=” + str;
xmlHttp.send(param);
}
//回调函数,对页面内容进行更新
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
$(“#t1″).val(response);
$(“#done”).append(response);
}
}
AJAX测试服务器端的servlet代码:
package andycpp;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Controller extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s = req.getParameter(“a”);
resp.setContentType(“text/xml”);
resp.setHeader(“Cache-Control”, “no-cache”);
resp.getWriter().write(s);
}
}