[持续更新]HTML5学习笔记(五)简单Ajax实现

1. Ajax

ajax现在已经广泛的应用在我们日常生活中,因为他可以实现不刷新页面,只替换文档中的一部分或多个部分。这大大的提升了用户体验和减少了页面显示不必要的内容。不过他也使浏览器的后退键时效,是一门有争议但是仍然广泛应用的技术。也是前端开发人员和后台开发人员都必须掌握的技术。

Ajax在网站中有大量的应用:一开始Google在他的搜索框中使用ajax匹配跟用户输入相似搜索结果而引起轰动。现在比如去哪网的机票查询,在网速较慢的情况下可以看到页面显示一个转菊花,之后才会显示全部内容,并且在选择不同日期的机票,会重复上述过程,注意地址栏,地址并没有变化。

下面由浅入深展示几个ajax实例。

项目源码在最后 项目源码在最后 项目源码在最后 

1.简单的ajax

页面中三个按钮,点击不同的按钮,页面下方的内容发生变化。

最简单的例子,这里不涉及后台的数据处理,只是简单地显示其他的页面。

项目结构:

 

Index.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>Ajax Sample Test</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">
  </head>
  
  <body>
  <button id="html">HTML</button><br>
  <button id="xml">XML</button><br>
  <button id="json">JOSN</button><br>
    <div id="target">
    	即将被替换区域
    </div>
  <script type="text/javascript">
  var buttons = document.getElementsByTagName("button");
  for(var i = 0; i < buttons.length; i++){
  	buttons[i].onclick = afterButtonsClick;
  }
 
  function afterButtonsClick(e) {
  	var httpRequest = new XMLHttpRequest();
  	httpRequest.onreadystatechange = afterResponse;
  	httpRequest.open("GET", e.target.id + ".jsp");
  	httpRequest.send();
  }
 
  function afterResponse(e){
  	if(e.target.readyState == XMLHttpRequest.DONE && e.target.status == 200){
  	 document.getElementById("target").innerHTML = e.target.responseText;
  	}
  }
  </script>
  </body>
</html>
 

 

首先获取三个按钮,并且给每个按钮绑定一个点击事件afterButtonsClick

改事件首先创建一个XMLHTTPRequest对象(该对象是浏览器内置对象,但是在老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象: xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");),并且为他的onreadystatechange 绑定事件afterResponse,并且目的地址发送get请求。

httpRequest对象的readyState 改变时触发事件afterResponse,只有当服务器响应请求成功时,将目标区域的内容替换成请求传输的内容。

XMLHttpRequest readyState属性的值

数值

说明

UNSENT

0

已创建XMLHttpRequest对象

OPEND

1

已调用open方法

HEADERS_RECEIVED

2

已收到服务器响应的标头

LOADING

3

已收到服务器相应

DONE

4

响应完成或已失败

 

注意的是DONE表示完成或失败,若要只表示成功需要加上条件http状态码为200

 

Ajax事件

XMLHttpRequest对象支持的一些功能比如:

名称

说明

返回值

Abort

在请求终止时触发

ProgressEvent

Error

在请求失败时触发

ProgressEvent

Load

在请求成功完成时触发

ProgressEvent

Loadend

在请求完成时触发,无论成功与否

ProgressEvent

Loadstart

在请求开始时触发

ProgressEvent

Progress

触发以提示请求的进度

ProgressEvent

Timeout

如果请求超时触发

ProgressEvent

Readystatechange

在请求周期的不同阶段触发

Event

 

ProgressEvent对象定义了Event对象的所有成员并增加了这些成员:

名称

说明

返回值

LengthComputable

如果能够计算数据流的总长度则返回true

布尔值

Loaded

返回当前已载入数据总量

数值

Total

返回可用的总数据量

数值

 

由于不同浏览器对这些事件的支持不统一,FF支持最完整,chrome部分支持,opera完全不支持,建议使用FF来测试下面代码:

修改的index.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>Ajax Sample Test</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">
  </head>
  
  <body>
  <button id="html">HTML</button><br>
  <button id="xml">XML</button><br>
  <button id="json">JOSN</button><br>
  <table id="event" border="1">
  
 
  </table>
    <div id="target">
    	即将被替换区域
    </div>
  <script type="text/javascript">
  var buttons = document.getElementsByTagName("button");
  for(var i = 0; i < buttons.length; i++){
  	buttons[i].onclick = afterButtonsClick;
  }
 
  function afterButtonsClick(e) {
  	clearEventDetails();
  	var httpRequest = new XMLHttpRequest();
  	httpRequest.onreadystatechange = afterResponse;
  	httpRequest.error = afterError;
  	httpRequest.onload = afterLoad;
  	httpRequest.onloadend = afterLoadEnd;
  	httpRequest.onloadstart = afterLoadStart;
  	httpRequest.onprogress = afterProgeress;
  	httpRequest.open("GET", e.target.id + ".jsp");
  	httpRequest.send();
  }
 
  function afterResponse(e){
  	if(e.target.readyState == XMLHttpRequest.DONE && e.target.status == 200){
  	 document.getElementById("target").innerHTML = e.target.responseText;
  	}
  }
 
  function afterError(e){displayEventDetails("error",e);}
  function afterLoad(e){displayEventDetails("load",e);}
  function afterLoadEnd(e){displayEventDetails("loadend",e);}
  function afterLoadStart(e){displayEventDetails("loadstart",e);}
  function afterProgeress(e){displayEventDetails("progeress",e);}
 
  function clearEventDetails(){
  	document.getElementById("event").innerHTML = "<tr><th>Event</th><th>lengthComputable</th>" + "<th>loaded</th><th>total</th></tr>"
  }
 
  function displayEventDetails(eventName ,e){
  	if(e){
  	 document.getElementById("event").innerHTML += "<tr><td>" + eventName + "</td><td>" + e.lengthComputable + "</td><td>" + e.loaded + "</td><td>" + e.total + "</td></tr>";
  	}
  	else {
  	 document.getElementById("event").innerHTML += "<tr><td>" + eventName + "</td><td>NA</td><td>NA</td><td>NA</td></tr>";
  	}
  }
  </script>
  </body>
</html>
 

下面举再一个例子,比第一个复杂一点了,这次涉及到后台的数据运算。

后台我演示的是servlet,例子是一个简单的超市收银台,根据卖多少水果收多少钱。

Index.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>Ajax Sample Test</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">
  </head>
  
  <body>
  <form id="demo" action="<%=basePath%>servlet/AjaxServlet">
  	<h1>超市收银台</h1>
  	<div>
  	 <label for="apple">苹果:</label>
  	 <input type="number" name="apple_num" value="2" id="apple">个
  	</div>
  	<div>
  	 <label for="banana">香蕉:</label>
  	 <input type="number" name="banana_num" value="3" id="banana">个
  	</div>
  	<div>
  	 <label for="strawberry">草莓:</label>
  	 <input type="number" name="strawberry_num" value="4"id="strawberry">个
  	</div>
  	<div>
  	 <p>总计:<span id="res"></span>元</p>
  	</div>
  	<div>
  	 <button type="submit" id="submit">确认购买</button>
  	</div>
  </form>
  <script type="text/javascript">
document.getElementById("submit").onclick = handleButtonPress;
var httpRequest;
function handleButtonPress(e) {
e.preventDefault();
var form = document.getElementById("demo");
var formData = "";
var inputElements = document.getElementsByTagName("input");
for(var i = 0; i < inputElements.length; i++){
formData += inputElements[i].name + "=" + inputElements[i].value + "&";
}
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleRespose;
httpRequest.open("POST", form.action);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(formData);
}
function handleRespose(){
if(httpRequest.readyState == 4 && httpRequest.status == 200){
document.getElementById("res").innerHTML = httpRequest.responseText;
}
}
  </script>
  </body>
</html>
 

  

Ajax.servlet

package com.test.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 {
 
/**
 * Constructor of the object.
 */
public AjaxServlet() {
super();
}
 
/**
 * Destruction of the servlet. <br>
 */
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
 
/**
 * The doGet method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to get.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 
}
 
/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String apple_num = request.getParameter("apple_num");
String banana_num = request.getParameter("banana_num");
String strawberry_num = request.getParameter("strawberry_num");
int total = Integer.parseInt(apple_num) * 5 + Integer.parseInt(banana_num) * 3 + Integer.parseInt(strawberry_num) * 10;
response.setContentType("text/html;charset=utf-8");  
  
        PrintWriter out = response.getWriter();  
  
        out.println(total);  
        out.flush();  
        out.close();  
}
 
/**
 * Initialization of the servlet. <br>
 *
 * @throws ServletException if an error occurs
 */
public void init() throws ServletException {
// Put your code here
}
 
}
 

这里的后台只是简单地向前台输出了一个变量,在实际的应用中往往需要向前台输出大量内容。 


源代码已上传,但是今天csdn下载区不知怎么打不开了 评论给链接

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页