一个简单的ajax实例,通过按钮改变一个div里的文本内容。以下3个文件在一个web工程中。
改变前:
改变后:
1.html文件,显示界面
<html>
<head>
<title>Ajax</title>
<script type="text/javascript">
var xmlhttp;
var url = "test";
function loadXMLDoc(){
if(window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
if(xmlhttp != null){
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else{alert("Your browser dose not support XMLHTTP.");}
}
function state_Change(){
if(xmlhttp.readyState==4 ){
if(xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else{
alert("Problem retrieving data:" +xmlhttp.statusText);
}
}
}
</script>
</head>
<body>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
<input type="button" οnclick="loadXMLDoc();" value="Change Content"/>
</body>
</html>
2.servlet中的关键代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("Hello World!");
out.close();
}
3.web.xml中的配置
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>com.lz.servlet.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>