19、Ajax剖析

来源:互联网 发布:网络骚扰电话怎么拦截 编辑:程序博客网 时间:2024/04/29 18:42

Ajax(Asynchronous JavaScript and XML),异步的JavaScript与XML,强调异步。

所谓异步,就是前一个操作还没完成,就可以进行下一个操作,提高用户体验,页面可以局部刷新,减少网络传输流量

1、Ajax中的一个重要对象是XMLHttpRequest。

2、使用Ajax准备向服务器端发送请求:xmlHttpRequest.open("GET","AjaxServlet",true);

一个Ajax使用实例:

<%@ 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 'ajax.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">var xmlHttpRequest = null; //声明一个空对象以接收XMLHttpRequest对象function ajaxSubmit(){if(window.ActiveXObject)//IE浏览器{xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");}else if(window.XMLHttpRequest)//除IE外的其他浏览器实现{xmlHttpRequest = new XMLHttpRequest();}if(null != xmlHttpRequest){xmlHttpRequest.open("GET","AjaxServlet",true);//关联好ajax的回调函数xmlHttpRequest.onreadystatechange = ajaxCallBack;//真正地向服务器端发送数据xmlHttpRequest.send(null);}}function ajaxCallBack(){if(xmlHttpRequest.readyState == 4){if(xmlHttpRequest.status == 200){var responseText = xmlHttpRequest.responseText;document.getElementById("div1").innerHTML = responseText;}}}</script>  </head>    <body>    <input type="button" value="get from server" onclick="ajaxSubmit();">    <div id="div1"></div>  </body></html>


调用的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 AjaxServlet extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{PrintWriter out = resp.getWriter();System.out.println("doGet invoke");out.println("hello world");out.flush();}}


对于上面的程序,如果在firefox中进行测试,点击一次按钮,就会在MyEclipse控制台打印一次doGet invoke,但是如果使用IE浏览器,则只是在第一次点击按钮时打印doGet invoke,此后再按就没有打印信息了。

上述原因是因为IE缓存的问题,将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 AjaxServlet extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{PrintWriter out = resp.getWriter();try{Thread.sleep(5000);}catch(Exception e){e.printStackTrace();}System.out.println("doGet invoke");resp.setHeader("pragma", "no-cache");resp.setHeader("cache-control", "no-cache");out.println("hello world");out.flush();}}


IE每次点击按钮都打印。

3、带参数的ajax实例 分别使用GET和POST进行传递:

页面ajax.jsp

<%@ 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 'ajax.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">var xmlHttpRequest = null; //声明一个空对象以接收XMLHttpRequest对象function ajaxSubmit(){if(window.ActiveXObject)//IE浏览器{xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");}else if(window.XMLHttpRequest)//除IE外的其他浏览器实现{xmlHttpRequest = new XMLHttpRequest();}if(null != xmlHttpRequest){var v1 = document.getElementById("value1ID").value;var v2 = document.getElementById("value2ID").value;//xmlHttpRequest.open("GET","AjaxServlet?v1=" + v1 + "&v2=" + v2,true);xmlHttpRequest.open("POST","AjaxServlet",true);//关联好ajax的回调函数xmlHttpRequest.onreadystatechange = ajaxCallBack;//真正地向服务器端发送数据//xmlHttpRequest.send(null); //对应GET方法的send//使用POST方式提交,必须要加上如下一行,不加这一行,传递参数v1=null  v2=nullxmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xmlHttpRequest.send("v1=" + v1 + "&v2=" + v2);}}function ajaxCallBack(){if(xmlHttpRequest.readyState == 4){if(xmlHttpRequest.status == 200){var responseText = xmlHttpRequest.responseText;document.getElementById("div1").innerHTML = responseText;}}}</script>  </head>    <body>    <input type="button" value="get from server" onclick="ajaxSubmit();"><br/>    <input type="text" name="value1" id="value1ID"><br/>    <input type="text" name="value2" id="value2ID" ><br/><div id="div1"></div>  </body></html>


接收请求的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 AjaxServlet extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{process(req, resp);}private void process(HttpServletRequest req, HttpServletResponse resp)throws IOException{String v1 = req.getParameter("v1");String v2 = req.getParameter("v2");System.out.println("v1=" + v1 + "  v2=" + v2);String v3 = String.valueOf(Integer.valueOf(v1) + Integer.valueOf(v2));PrintWriter out = resp.getWriter();/*try{Thread.sleep(5000);}catch(Exception e){e.printStackTrace();}*/System.out.println("doGet invoke");resp.setHeader("pragma", "no-cache");resp.setHeader("cache-control", "no-cache");out.println(v3);out.flush();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{System.out.println("doPost invoke");this.process(req, resp);}}


 

原创粉丝点击