ajax简单实例
ajax简单实例
(js内产生xmlHttpRequest,它和servlet交互返回xml显示在页面)
---------------------------------AJAX.html-------------------------------------------
<html>
<head>
<title>AJAX.html</title>
</head>
<script type="text/javascript">
/*通过异步传输XMLHTTP发送参数到ajaxServlet,返回符合条件的XML文档*/
function getResult(){
var url = "ajaxServlet?action=send";
if (window.XMLHttpRequest){
req = new XMLHttpRequest();
}else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req)
{
req.open("GET",url, true);
req.onreadystatechange = complete;
req.send(null);
}
}
/*分析返回的XML文档*/
function complete(){
if (req.readyState == 4)
{
if (req.status == 200){
var type = req.responseXML.getElementsByTagName("type_name");
var str=new Array();
for(var i=0;i<type.length;i++){
str[i]=type[i].firstChild.data;
document.all[td].innerHTML+=str[i]+"<BR>";
}
}
}
}
</script>
<body onLoad="getResult()">
<table width="80%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td id="td">
</td>
</tr>
</table>
</body>
</html>
---------------------------------ajaxServlet.java-----------------------------------------------------
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{
private static final String CONTENT_TYPE = "text/xml; charset=gb2312";
public void init() throws ServletException{}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
if (("send").equals(action))
{
StringBuffer sb = new StringBuffer("<type>");
sb.append("<type_name>AA</type_name>");
sb.append("<type_name>BB</type_name>");
sb.append("<type_name>CC</type_name>");
sb.append("<type_name>DD</type_name>");
sb.append("</type>");
out.write(sb.toString());
out.close();
}
}
}
--------------------------------web.xml------------------------------------------------------
<?xml version = 1.0 encoding = UTF-8?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<description>Empty web.xml file for Web Application</description>
<servlet>
<servlet-name>ajax</servlet-name>
<servlet-class>ajaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ajax</servlet-name>
<url-pattern>/ajaxServlet</url-pattern>
</servlet-mapping>
</web-app>
补充:综合编程 , 其他综合 ,