此小程序主要给ajax还未入门的朋友们一个简单的演示程序的主要内容就是将页面部分的id通过表单传到java的servlet中因为只是做示例所以没有对id进行任何处理有兴趣的朋友可以连接数据库或应用一些jdk方法进行处理操作等等在此仅作示例话不多说了(这话就不少了)看代码吧
ajaxdemojsp <%@ page language=java pageEncoding=GB%>
<!DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN>
<html>
<head>
<title>My JSP ajaxdemojsp starting page</title>
<script type=text/javascript>
var req;
function createAJAX() {
if(windowXMLHttpRequest) {
req = new XMLHttpRequest();
} else if(windowActiveXObject) {
req = new ActiveXObject(MicrosoftXMLHTTP);
}
}
function testAjax() {
var url = /testajax/servlet/TestAjaxServlet?id=;
createAJAX();
reqopen(POST url true);
reqonreadystatechange = callback;
reqsend(null);
}
function callback() {
if(reqreadyState == ) {
if(reqstatus == ) {
documentgetElementById(ajaxDiv)innerHTML = reqresponseText;
}
}
}
</script>
</head>
<body>
<input type=button value=测试ajax name=button id=ajaxButton onclick=testAjax()><br>
可以根据下边这个id号进行操作<div id=ajaxDiv></div>
</body>
</html>
说明因为只是一个简简单单的玩意所以页面部分未使用任何ajax框架只是用最基本的ajax原理实现页面会将id通过ajax传到后台
webxml
<?xml version= encoding=UTF?>
<webapp version=
xmlns=
xmlns:xsi=instance
xsi:schemaLocation=
app__xsd>
<servlet>
<servletname>TestAjaxServlet</servletname>
<servletclass>comajaxTestAjaxServlet</servletclass>
</servlet>
<servletmapping>
<servletname>TestAjaxServlet</servletname>
<urlpattern>/servlet/TestAjaxServlet</urlpattern>
</servletmapping>
<welcomefilelist>
<welcomefile>ajaxdemojsp</welcomefile>
</welcomefilelist>
</webapp>
说明既然用到servlet了那难免要配置一下webxml了将对应servlet信息配置在webxml中
TestAjaxServletjava
package comajax;
import javaioIOException;
import javaioPrintWriter;
import javaxservletServletException;
import javaxservlethttpHttpServlet;
import javaxservlethttpHttpServletRequest;
import javaxservlethttpHttpServletResponse;
@SuppressWarnings(serial)
public class TestAjaxServlet extends HttpServlet {
public void doPost(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
responsesetContentType(text/html);
String id = requestgetParameter(id);
//可在此处判断id是否为空并根据id做你相应的处理随意!
PrintWriter out = responsegetWriter();
outprintln(<!DOCTYPE HTML PUBLIC \//WC//DTD HTML Transitional//EN\>);
outprintln(<HTML>);
outprintln( <HEAD><TITLE>A Servlet</TITLE></HEAD>);
outprintln( <BODY>);
outprint(id);
outprintln( </BODY>);
outprintln(</HTML>);
outflush();
outclose();
}
说明写一个最最……简单的doPost方法可以加上你自己的代码处理完了id把它毫不留情的扔回页面然后看看结果吧
结尾谨献给接触java web希望了解ajax但又在迷茫中的朋友