AJAX客戶端與服務(wù)端,可以在[不刷新整個瀏覽器]的情況下,與服務(wù)器進(jìn)行異步通信的技術(shù)。即ajax是一個[局部刷新]的異步通信技術(shù),AJAX技術(shù)不是全新的語言,時2005年谷歌公司提出的一種全新的編程模式,不是新的編程語言。
傳統(tǒng)web應(yīng)用請求和響應(yīng)的特點(diǎn)
( 1 )請求:瀏覽器以 HTTP 協(xié)議的方式提交請求到服務(wù)器
( 2 )響應(yīng):服務(wù)器以 HTTP 協(xié)議的方式響應(yīng)內(nèi)容到瀏覽器
注意: HTTP 是 WEB 大眾化非安全協(xié)議
HTTPS 是 WEB 安全協(xié)議,是基于 HTTP 協(xié)議的,且加了一些加密等特殊功能,常用于在線支付,或者是需要安全性較高的網(wǎng)站中,例如: 12306 網(wǎng)站
HTTP 請求有三個部份組成:請求行,請求頭,請求體
HTTP 響應(yīng)有三個部份組成:響應(yīng)行,響應(yīng)頭,響應(yīng)體
( 3 )狀態(tài)欄:有明顯的進(jìn)度條刷新現(xiàn)象,如果服務(wù)器響應(yīng)較慢的話,進(jìn)度條刷新也會變慢, IE9 等中高版本瀏覽器,有明顯轉(zhuǎn)圈圈圖標(biāo)
( 4 )歷史欄:會收集原來已訪問過的 web 頁面,進(jìn)行緩存
( 5 )缺點(diǎn):不需變化的大量數(shù)據(jù),也全部刷新,造成瀏覽器加載和處理負(fù)擔(dān)
( 6 )可改進(jìn)的地方:讓不需變化的大量數(shù)據(jù),原封不動,不用緩存到歷史欄中,無需全部刷新,只刷新某些需要變化的數(shù)據(jù)區(qū)域.
ajax異步獲取時間的實(shí)例
<%--
Created by IntelliJ IDEA.
User: cxspace
Date: 16-8-16
Time: 上午8:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>無需刷新整個web頁面顯示服務(wù)器響應(yīng)時間</title>
</head>
<body>
當(dāng)前時間
<span id = "time"></span> <br>
<input id="buttonID" type="button" value="獲取當(dāng)前時間">
<br>
<script type="text/javascript">
//創(chuàng)建ajax對象
function createAJAX() {
var ajax = null;
try {
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch (e1){
try {
ajax = new XMLHttpRequest();
}catch (e2){
alert("你的瀏覽器不支持異步對象,請更換瀏覽器");
}
}
return ajax;
}
</script>
<script type="text/javascript">
document.getElementById("buttonID").onclick = function () {
//1.創(chuàng)建ajax異步對象
var ajax = createAJAX();
//2.準(zhǔn)備發(fā)送請求
var method = "GET";
var url = "${pageContext.request.contextPath}/AjaxTimeServlet?time="+new Date().getTime();
ajax.open(method,url);
//3.真正發(fā)送請求體數(shù)據(jù)到服務(wù)器,如果請求體中沒有內(nèi)容,用null表示
ajax.send(null);
//==========等待
//4.ajax異步對象不斷監(jiān)聽服務(wù)器的狀態(tài)0-1-2-3-[4]
// 一定要狀態(tài)變化后,才觸發(fā)function函數(shù)
// 如果狀態(tài)永遠(yuǎn)時4-4-4-4-4,不會觸發(fā)function(){}函數(shù)
ajax.onreadystatechange = function () {
//如果狀態(tài)碼是4
if (ajax.readyState == 4){
//如果響應(yīng)碼是200
if (ajax.status == 200){
//5.用ajax異步對象中獲取數(shù)據(jù)
var nowStr = ajax.responseText;
var spanElement = document.getElementById("time");
spanElement.innerHTML = nowStr;
}
}
}
}
</script>
</body>
</html>
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by cxspace on 16-8-16.
*/
public class AjaxTimeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowStr = sdf.format(new Date());
// System.out.println("拿到時間");
//以流的方式響應(yīng)到ajax異步對象中
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(nowStr);
pw.flush();
pw.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
什么是 AJAX 【 Asynchronous 異步的 JS 和 XML 】,工作原理與特點(diǎn)
( 1 )什么是同步:
請求 1-> 響應(yīng) 1-> 請求 2-> 響應(yīng) 2->
Web1.0 時代
( 2 )什么是異步:
請求 1-> 請求 2-> 請求 3-> 響應(yīng) 1-> 響應(yīng) 2-> 響應(yīng) 3->
請求 1-> 響應(yīng) 1-> 請求 2-> 請求 3-> 響應(yīng) 2-> 響應(yīng) 3->
Web2.0 時代
項(xiàng)目中: Web1.0 為主(整個瀏覽器刷新), Web2.0 為輔(瀏覽器局部刷新)
( 3 )什么是 AJAX
客戶端(特指 PC 瀏覽器)與服務(wù)器,可以在【不必刷新整個瀏覽器】的情況下,與服務(wù)器進(jìn)行異步通訊的技術(shù)
即, AJAX 是一個【局部刷新】的【異步】通訊技術(shù)
AJAX 不是全新的語言,是 2005 年 Google 公司推出的一種全新【編程模式】,不是新的編程語言
( 4 )不用刷新整個頁面便可與服務(wù)器通訊的辦法有:
( A ) Flash/ActionScript
( B )框架 Frameset
( C ) iFrame (內(nèi)嵌入框架 )
( D ) XMLHttpRequest( 非 IE 瀏覽器 ) 和 ActiveXObject(IE 瀏覽器 )
背景:早上 IE5 時,微軟就開發(fā)出了第一個異步通訊對象,叫 ActiveXObject 對象,
Firefox 等其它瀏覽器廠商也慢慢引入異步通訊對象,叫 XMLHttpRequest 對象,
IE 的高版本,也將這個異步對象取名叫 XMLHttpRequest 對象,但 IE 有向下兼容問題,
也可以使用 ActiveXObject 對象。
無需第三方 jar 包,現(xiàn)代中高版本瀏覽器中內(nèi)置了這個異步通訊對象,只需通過 JavaScript 就可以創(chuàng)建
注意:所有瀏覽器中都內(nèi)置了異步對象,在默認(rèn)情況下,該異步對象并沒有創(chuàng)建出來
function createAJAX(){
var ajax = null;
try{
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch(e1){
ajax = new XMLHttpRequest();
}
return ajax;
}
( 5 ) AJAX 工作原理
( 6 ) AJAX 包含的技術(shù)
( 7 ) AJAX 開發(fā)步驟
步一:創(chuàng)建 AJAX 異步對象,例如: createAJAX()
步二:準(zhǔn)備發(fā)送異步請求,例如: ajax.open(method,url)
步三:如果是 POST 請求的話,一定要設(shè)置 AJAX 請求頭,例如: ajax.setRequestHeader()
如果是 GET 請求的話,無需設(shè)置設(shè)置 AJAX 請求頭
步四:真正發(fā)送請求體中的數(shù)據(jù)到服務(wù)器,例如: ajax.send()
步五: AJAX 不斷的監(jiān)聽服務(wù)端響應(yīng)的狀態(tài)變化,例如: ajax.onreadystatechange ,后面寫一個無名處理函數(shù)
步六:在無名處理函數(shù)中,獲取 AJAX 的數(shù)據(jù)后,按照 DOM 規(guī)則,用 JS 語言來操作 Web 頁面
( 8 ) AJAX 適合用在什么地方
AJAX 【適合】不用來傳遞大量數(shù)據(jù),而只用來【傳遞少量數(shù)據(jù)】,在用戶的【體驗(yàn)】上,【更加人性化】
AJAX 是一個和服務(wù)器無關(guān)的技術(shù),即服務(wù)器可使用: JavaEE , .NET , PHP ,。。。這些技術(shù)都可
AJAX 只管向服務(wù)器發(fā)送請求,同時只管接收服務(wù)器的 HTML 或 XML 或 JSON 載體響應(yīng)
服務(wù)端不能使用轉(zhuǎn)發(fā)或重定向到 web 頁面,因?yàn)檫@樣會起瀏覽器全面刷新
即只能以流的方式響應(yīng)給瀏覽器
AJAX異步方式實(shí)現(xiàn)驗(yàn)證實(shí)例(GET方式)
<%--
Created by IntelliJ IDEA.
User: cxspace
Date: 16-8-16
Time: 下午7:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>以get方式異步檢查數(shù)據(jù)庫中是否已經(jīng)存在該用戶</title>
</head>
<body>
<form>
用戶名:<input id="usernameID" type="text" name="username"/>
光標(biāo)移出后立即檢查結(jié)果
</form>
<hr>
<span id="resID"></span>
<script type="text/javascript">
function createAJAX() {
var ajax = null;
try {
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch (e1){
try {
ajax = new XMLHttpRequest();
}catch (e2){
alert("你的瀏覽器不支持ajax,請更換瀏覽器")
}
}
return ajax;
}
</script>
<script type="text/javascript">
document.getElementById("usernameID").onblur = function () {
var username = this.value;
if(username.length == 0){
document.getElementById("resID").innerHTML = "用戶名必填";
}else {
username = encodeURI(username);
// alert(username)
var ajax = createAJAX();
// alert("創(chuàng)建ajax ok")
var method = "GET";
var url="${pageContext.request.contextPath}/UserServlet?time="+new Date().getTime()+"&username="+username;
ajax.open(method,url);
ajax.send(null);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4){
if (ajax.status == 200){
var tip = ajax.responseText;
document.getElementById("resID").innerHTML = tip;
}
}
}
}
}
</script>
</body>
</html>
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by cxspace on 16-8-16.
*/
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
System.out.println(username);
String tip = "<font color='green'> 可以注冊 </front>";
if ("杰克".equals(username)){
tip = "<font color='red'> 該用戶已經(jīng)存在 </front>";
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(tip);
pw.flush();
pw.close();
}
}
以POST的方式實(shí)現(xiàn)異步驗(yàn)證實(shí)例
注意點(diǎn):content中鍵值對表達(dá)式絕對不能有空格
<%--
Created by IntelliJ IDEA.
User: cxspace
Date: 16-8-17
Time: 上午9:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>以post方式驗(yàn)證檢查注冊的用戶名是否在數(shù)據(jù)庫中存在</title>
<script type="text/javascript" src="js/ajax.js"></script>
</head>
<body>
用戶名[POST]: <input id="usernameID" type="text" />
<span id="resID">
</span>
<hr/>
<script type="text/javascript">
document.getElementById("usernameID").onblur = function () {
var username = this.value;
// alert(username);
var ajax = createAJAX();
var method = "POST";
var url = "${pageContext.request.contextPath}/UserServlet?time="+new Date().getTime();
ajax.open(method,url);
//設(shè)置ajax請求頭為post,他會將請求體中的漢字自動進(jìn)行utf-8的編碼
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
//******鍵值對中間不能有空格,例如 username = aa; 服務(wù)端拿到為null
var content = "username="+ username;
ajax.send(content);
//wait
ajax.onreadystatechange = function () {
if (ajax.readyState == 4){
if (ajax.status == 200){
var tip = ajax.responseText;
var imgElement = document.("img");
imgElement.src = tip;
imgElement.style.width="12px";
imgElement.style.height="12px";
var spanElement = document.getElementById("resID");
spanElement.innerHTML = "";
spanElement.appendChild(imgElement);
}
}
}
}
</script>
</body>
</html>
package servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by cxspace on 16-8-16.
*/
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
// System.out.println(username);
String tip = "images/MsgSent.gif";
if ("杰克".equals(username)){
tip = "images/MsgError.gif";
}
System.out.println(tip);
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(tip);
pw.flush();
pw.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
System.out.println(username);
String tip = "<font color='green'> 可以注冊 </front>";
if ("杰克".equals(username)){
tip = "<font color='red'> 該用戶已經(jīng)存在 </front>";
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(tip);
pw.flush();
pw.close();
}
}
文章來源:博客園