Ajax的初级使用
一、AJAX簡介(本文的例子都使用的是原生的ajax)
老技術新用法
二、異步和同步區別
三、XMLHttpRequest對象(面試題)
屬性:
readyState:
0:未初始化
1:open方法已經調用了
2:send方法已經調用了
3:接收到了響應消息頭,但沒有接收到正文
4:接收到了響應正文。響應結束
responseText:只讀的。返回的是String
作用:接收服務器返回的文本類型的正文數據。
responseXML:只讀的。返回的是Document對象(JS中文檔模型)
作用:接收服務器返回的XML類型的正文數據。
status:只讀的。返回的是short
作用:接收服務器返回的響應狀態碼
statusText:只讀的。返回的是String
作用:接收服務器返回的響應嗎描述
方法:
l?open(String method,String url,boolean async):建立與服務器的鏈接。
method:請求方式。GET|POST
url:請求的服務器地址。
async:是否是異步。true是異步的。默認就是true。
l?send(String data):發出請求。data參數是請求正文的內容數據。
l?setRequestHeader(String headerName,String headerValue):設置請求消息頭。
l?getAllResponseHeaders():返回所有的響應消息頭。是一個String字符串。
l?getResponseHeader(headerName):返回指定頭的值。是一個String字符串。
事件處理器:onreadystatechange:執向一個函數。XMLHttpRequest對象的readyState的每次變化都會觸發onreadystatechange指向的事件處理器。
四、GET和POST請求的發送
五、服務器端返回的數據類型:
XML: 返回的是xml對象
JSON:返回的是文本類型,需要轉換
?
編碼步驟:
1 function getXHR() { 2 var xmlHttp; 3 4 try { 5 // Firefox, Opera 8.0+, Safari 6 xmlHttp = new XMLHttpRequest(); 7 } catch (e) { 8 9 // Internet Explorer 10 try { 11 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 12 } catch (e) { 13 14 try { 15 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 16 } catch (e) { 17 alert("您的瀏覽器不支持AJAX!"); 18 return false; 19 } 20 } 21 } 22 return xmlHttp; 23 } util.js 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <title>AJAX的編碼步驟:測試異步交互是可行的</title> 7 8 <meta http-equiv="pragma" content="no-cache"> 9 <meta http-equiv="cache-control" content="no-cache"> 10 <meta http-equiv="expires" content="0"> 11 <!-- 12 <link rel="stylesheet" type="text/css" href="styles.css"> 13 --> 14 <script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script> 15 <script type="text/javascript"> 16 window.οnlοad=function(){ 17 //window.onload是一個事件,當文檔加載完成之后觸發該事件 18 document.getElementById("bt1").οnclick=function(){ 19 //發出異步請求:步驟 20 21 //1、得到xhr(XMLHttpRequest)對象 22 var xhr = getXHR(); 23 //2、注冊狀態變化監聽器 24 xhr.onreadystatechange=function(){ 25 //做出具體的處理 26 if(xhr.readyState==4){//接收到了響應正文。響應結束 27 if(xhr.status==200){//200:服務器成功返回頁面 28 alert("服務器已經響應結束了,去看看吧"); 29 } 30 } 31 } 32 //3、建立與服務器的鏈接 33 //如果訪問的地址相同,瀏覽器就不會真正的發出請求 ?time="+new Date().getTime() 34 xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo1?time="); 35 //4、向服務器發出請求 36 xhr.send(null);//沒有正文 37 } 38 } 39 </script> 40 </head> 41 42 <body> 43 <input id="bt1" type="button" value="點我呀"/> 44 <%-- 45 不論type是什么類型,只要單擊鼠標就會執行,window.load=function事件 46 --%> 47 </body> 48 </html> View Code?
一個驗證用戶名是否存在例子:(理解POST和GET提交時send方法傳值的區別)
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <title>檢測用戶名是否可用</title> 7 8 <meta http-equiv="pragma" content="no-cache"> 9 <meta http-equiv="cache-control" content="no-cache"> 10 <meta http-equiv="expires" content="0"> 11 <script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script> 12 <!-- 13 <link rel="stylesheet" type="text/css" href="styles.css"> 14 --> 15 <script type="text/javascript"> 16 window.οnlοad=function(){ 17 document.getElementById("username").οnblur=function(){//失去焦點 18 if(this.value==""){ 19 alert("請輸入用戶名"); 20 this.focus();//恢復焦點 21 return; 22 } 23 //發出異步請求 24 var xhr = getXHR(); 25 xhr.onreadystatechange=function(){ 26 if(xhr.readyState==4){ 27 if(xhr.status==200){ 28 29 document.getElementById("msg").innerHTML=xhr.responseText; 30 //responseText接收服務器返回的文本類型的正文數據。 31 //放到名為msg的span(屬于一個行內元素)中 32 } 33 } 34 } 35 /*GET提交時,在send中傳值是不起作用的; 36 xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo2?username="+this.value+"&time="+new Date().getTime()); 37 xhr.send(null); 38 */ 39 40 // 41 xhr.open("POST","${pageContext.request.contextPath}/servlet/ServletDemo2?time="+new Date().getTime()); 42 //設置請求消息頭:告知客戶端提交的正文的MIME類型 43 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 44 xhr.send("username="+this.value); 45 } 46 } 47 </script> 48 </head> 49 50 <body> 51 <form action="" method="post"> 52 用戶名:<input type="text" id="username" name="username"/><span id="msg"></span><br/> 53 密碼:<input type="password" id="password" name="password"/><br/> 54 <input type="submit" value="注冊"/> 55 </form> 56 </body> 57 </html> 頁面 1 package com.itheima.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 public class ServletDemo2 extends HttpServlet { 11 private String usernames[] = {"admin","wzhting"};//預先存在的用戶名,也可連接數據庫取;此處只是為了說明ajax做了簡化處理 12 13 public void doGet(HttpServletRequest request, HttpServletResponse response) 14 throws ServletException, IOException { 15 String username = request.getParameter("username"); 16 boolean b = false;//是否可用 17 for(String s:usernames){ 18 if(s.equals(username)){ 19 b = true; 20 break; 21 } 22 } 23 24 response.setContentType("text/html;charset=UTF-8"); 25 if(b){ 26 response.getWriter().write("<font color='red'>用戶名不可用</font>"); 27 }else{ 28 response.getWriter().write("<font color='green'>用戶可用</font>"); 29 } 30 31 } 32 33 public void doPost(HttpServletRequest request, HttpServletResponse response) 34 throws ServletException, IOException { 35 doGet(request, response); 36 } 37 38 } ServletDemo2?
一個理解(利用jsp頁面返回數據)例子:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <title>顯示所有的商品</title> 7 8 <meta http-equiv="pragma" content="no-cache"> 9 <meta http-equiv="cache-control" content="no-cache"> 10 <meta http-equiv="expires" content="0"> 11 <script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script> 12 <!-- 13 <link rel="stylesheet" type="text/css" href="styles.css"> 14 --> 15 <style type="text/css"> 16 .odd{ 17 background-color: #c3f3c3; 18 } 19 .even{ 20 background-color: #f3c3f3; 21 } 22 </style> 23 <script type="text/javascript"> 24 var flag = false; 25 window.οnlοad=function(){ 26 document.getElementById("bt1").οnclick=function(){ 27 //發出異步請求 28 var xhr = getXHR(); 29 xhr.onreadystatechange=function(){ 30 if(xhr.readyState==4){ 31 if(xhr.status==200){ 32 if (flag == false) { 33 document.getElementById("d1").innerHTML=xhr.responseText;// 文本類型 text/* 34 flag = true; 35 } else { 36 document.getElementById("d1").innerHTML=""; 37 flag = false; 38 } 39 } 40 } 41 } 42 xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo3?time="+new Date().getTime()); 43 xhr.send(null); 44 } 45 } 46 </script> 47 </head> 48 49 <body> 50 <input type="button" id="bt1" value="顯示商品"/> 51 <hr/> 52 <div id="d1"></div> 53 </body> 54 </html> 主頁面 1 package com.itheima.servlet; 2 3 import java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import com.itheima.domain.Product; 13 14 public class ServletDemo3 extends HttpServlet { 15 private List<Product> products = new ArrayList<Product>(); 16 public void init() throws ServletException { 17 products.add(new Product(1, "充氣筒", 20)); 18 products.add(new Product(2, "三國殺", 10)); 19 products.add(new Product(3, "撲克", 10)); 20 products.add(new Product(4, "洗衣粉", 10)); 21 products.add(new Product(5, "肥皂", 7)); 22 } 23 24 public void doGet(HttpServletRequest request, HttpServletResponse response) 25 throws ServletException, IOException { 26 request.setAttribute("products", products); 27 request.getRequestDispatcher("/listProducts.jsp").forward(request, response); 28 //jsp頁面因為是先編譯成servlet在運行的,而servlet中的jsp頁面就變成了如下形式的代碼 29 //out.write("<html>\r\n"); 30 //所以response的是整個jsp頁面 31 } 32 33 public void doPost(HttpServletRequest request, HttpServletResponse response) 34 throws ServletException, IOException { 35 doGet(request, response); 36 } 37 38 } ServletDemo3 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <title>title</title> 7 8 <meta http-equiv="pragma" content="no-cache"> 9 <meta http-equiv="cache-control" content="no-cache"> 10 <meta http-equiv="expires" content="0"> 11 <!-- 12 <link rel="stylesheet" type="text/css" href="styles.css"> 13 --> 14 15 </head> 16 17 <body> 18 <table border="1" width="438"> 19 <tr> 20 <th>編號</th><%-- th比表示標題的一格,會自動加黑加粗 --%> 21 <th>名稱</th> 22 <th>單價</th> 23 </tr> 24 <c:forEach items="${products}" var="p" varStatus="vs"> 25 <tr class="${vs.index%2==0?'odd':'even' }"> 26 <td>${p.id}</td> 27 <td>${p.name}</td> 28 <td>${p.price}</td> 29 </tr> 30 </c:forEach> 31 </table> 32 </body> 33 </html> 返回數據的jsp頁面結果表明:jsp頁面因為是先編譯成servlet再運行的,故jsp頁面會變成了如下形式的代碼:
out.write("<html>\r\n");out.write("\t<head>\r\n");out.write("\t\t<title>title</title>\r\n");out.write("\t</head>\r\n");out.write("\t<bodystyle=\"background-color:lightblue\">\r\n");out.write("\r\n");……
//所以jsp頁面可以返還給xhr.responseText;即使servlet中沒有response.getWriter().write("……");
?
轉載于:https://www.cnblogs.com/mmzs/p/7755728.html
總結
- 上一篇: 【bzoj3033】太鼓达人 DFS欧
- 下一篇: BZOJ3173 [TJOI2013]最