@H_301_1@这个例子可以比较基础。高手请跳过。本人刚学ajax,觉得好强大。
@H_301_1@
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <script type="text/javascript" src="scripts/jquery-1.4.4.js"></script> <script type="text/javascript"> $(function(){ $("#button1").click(function(){ $.ajax({ type: "GET",url: "Myservlet",dateType: "html",data:{'param1':$("#param1").val(),'param2':$("#param2").val()},success: function(returnedData){ $("#result").val(returnedData); } }); }); }); </script> </head> <body> <input type="text" id="param1">+ <input type="text" id="param2">= <input type="text" id="result"> <input type="button" value="get content from server" id="button1"> </body> </html>
页面运行的结果截图如下:
@H_301_1@
@H_301_1@2:在web.xml(这里没有用struts,如果用了也可以在那里配置)中配置一个action。
@H_301_1@
<servlet> <servlet-name>Myservlet</servlet-name> <servlet-class>servlet.Myservlet</servlet-class> </servlet> <servlet> <servlet-mapping> <servlet-name>Myservlet</servlet-name> <url-pattern>/Myservlet</url-pattern> </servlet-mapping>
3:写一个servlet:
@H_301_1@
package 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 Myservlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { int param1=Integer.parseInt(req.getParameter("param1")); int param2=Integer.parseInt(req.getParameter("param2")); resp.setHeader("pragma","no-cache"); resp.setHeader("cache-control","no-cache"); PrintWriter out = resp.getWriter(); //把该结果返回到ajax.jsp页面中的result文本框 //out.println("helloworld");//用于测试 out.println(String.valueOf(param1+param2)); out.flush(); } @Override protected void doGet(HttpServletRequest req,IOException { doPost(req,resp); } }
我们可以看到结果,但是前面2个值依然还在,这就是异步的强大之处,好多时候我们想获取数据,必须提交表单。刷新页面,但有时我们不想刷新页面,也想获取数据。就可以采用这种办法。如果我们在用百度搜索的时候,你写几个字,它马上就会出来提示,而且是最热门的搜索词汇。就是采用异步的方法得到的。下次也下个这样的帖子。