日期:2014-05-16 浏览次数:20827 次
一、Ajax介绍:
二、Ajax好处:
??? 传统的网络应用程序会将输入的信息提交给服务器(使用HTML表单),在服务器通过代码后,将会把一个全新的完整的页面传送给用户,由于用户每次提交输入信息的时候服务器都将传回一个新的页面,传统的网络应用程序通常运行缓慢且使用不便,使用AJAX,整个网页就可以于服务器之间局部的发送或者接收数据。
三、同步、异步:
四、XMLHttpRequest对象:
五、实例:
??? 1、传统方式客端与服务器传输数据:
?
??? myHtml.jsp
<%@ page contentType="text/html; charset=utf-8" language="java" %> <%@page import="java.net.URLDecoder"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; String message=""; if(request.getParameter("message")!=null && !request.getParameter("message").equals("")) { message=new String(request.getParameter("message").getBytes("ISO-8859-1"),"utf8"); } %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>公众AJAX教程-1</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"> <script type ="text/javascript" language ="javascript" > function sendRequest(url) { form1.action=url; form1.submit(); } </script> </head> <body> <form name="form1" id="form1" method="get" action=""> <dir> <%=message %> </dir> <input id="button1" type="button" value="获取数据" onclick ="sendRequest('htmlServer.jsp')"/> </form> </body> </html>
?
?? htmlServer.jsp?
<%@ page contentType="text/html; charset=utf-8" language="java" %> <%@page import="java.net.URLEncoder"%> <% //response.sendRedirect("myHtml.jsp?message=html调用成功");这种方式传递中文会出现乱码 response.sendRedirect("myHtml.jsp?message="+URLEncoder.encode("html调用成功","utf8")); %>
??? 2、Ajax方式客端与服务器传输数据:
???
??? myAjax.jsp
<%@ page contentType="text/html; charset=utf-8" language="java"%> <% 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> <title>公众AJAX教程-1</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"> <script type ="text/javascript" language ="javascript" > var XMLHttpReq=false; //定义变量,用来创建xmlhttprequest对象 function creatXMLHttpRequest() // 创建xmlhttprequest {