第一章: 基礎
1.1 是什么?
AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。
??AJAX 不是新的編程語言,而是一種使用現有標準的新方法。
??AJAX 是與服務器交換數據并更新部分網頁的藝術,在不重新加載整個頁面的情況下。
1.2 簡介
AJAX = 異步 JavaScript 和 XML。
??AJAX 是一種用于創建快速動態網頁的技術。
??通過在后臺與服務器進行少量數據交換,AJAX 可以使網頁實現異步更新。這意味著可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。
1.3 實例
w3c上并沒有給出實例……
第二章: Ajax XHR
2.1 XHR 創建對象(AJAX - 創建 XMLHttpRequest 對象
)
??XMLHttpRequest 是 AJAX 的基礎。
2.1.1 創建 XMLHttpRequest 對象的語法:
variable = new XMLHttpRequest();
2.2.2 老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 對象:
variable = new ActiveXObject("Microsoft.XMLHTTP");
2.2.3 為了應對所有的現代瀏覽器,包括 IE5 和 IE6,請檢查瀏覽器是否支持 XMLHttpRequest 對象。如果支持,則創建 XMLHttpRequest 對象。如果不支持,則創建 ActiveXObject :
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
2.2 XHR 請求(AJAX - 向服務器發送請求)
XMLHttpRequest 對象用于和服務器交換數據。
2.2.2 向服務器發送請求
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
2.2.3 POST OR GET?
GET 還是 POST?
??與 POST 相比,GET 更簡單也更快,并且在大部分情況下都能用。
然而,在以下情況中,請使用 POST 請求:
- 無法使用緩存文件(更新服務器上的文件或數據庫)
- 向服務器發送大量數據(POST 沒有數據量限制)
- 發送包含未知字符的用戶輸入時,POST 比 GET 更穩定也更可靠
2.2.4 為了避免得到緩存結果,向url添加一個唯一id
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
2.2.5 如果需要像 HTML 表單那樣 POST 數據,請使用 setRequestHeader() 來添加 HTTP 頭。
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
** 請記住,JavaScript 會等到服務器響應就緒才繼續執行。如果服務器繁忙或緩慢,應用程序會掛起或停止。**
2.3 XHR 響應(AJAX - 服務器響應)
2.3.1 服務器響應
如需獲得來自服務器的響應,請使用 XMLHttpRequest 對象的 responseText 或 responseXML 屬性。
例子:(獲取xml中的帶title標簽的文字)
Test01.htm
<html>
<head>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
var txt, x, i;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
xmlDoc = xmlhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("title");
for (i = 0; i < x.length; i++) {
txt = txt + x[i].childNodes[0].nodeValue + "<br />";
}
document.getElementById("myDiv").innerHTML = txt;
}
}
xmlhttp.open("GET", "books.xml", true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>My Book Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">獲得我的圖書收藏列表</button>
</body>
</html>
books.xml(里面有部分測試代碼)
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book>
<title>中華手記</title>
<introduce>一個字,好!</introduce>
<title>2018-12-12</title>
</book>
<book>
<title>三字經</title>
<introduce>一個字,好!</introduce>
<date>2018-12-12</date>
</book>
</books>
2.4 XML readState(AJAX - onreadystatechange 事件)
代碼:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
例子:(獲取txt里的文字)
Test02Txt.htm
<html>
<head>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "Test01.txt", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">通過 AJAX 改變內容</button>
</body>
</html>
Test01.txt
hello,welcome to my world!<br/>
what do you want ?
第三章 Ajax 高級
3.1 Ajax asp/php
例子:
Test03.asp
<html>
<head>
<script type="text/javascript">
function showHint(str) {
var xmlhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "test03.aspx?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>請在下面的輸入框中鍵入字母(A - Z):</h3>
<form action="">
姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>建議:<span id="txtHint"></span></p>
</body>
</html>
test03.asp
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test03.aspx.cs" Inherits="Ajax小實例.test03" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
//這里是空的
</div>
</form>
</body>
</html>
test03.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/plain";
string q = Request["q"];
string [] a = new string[5];
a[0] = "Anna";
a[1] = "Bnna";
a[2] = "cnna";
a[3] = "dnna";
a[4] = "enna";
if (q.Length > 0)
{
for (int i = 0; i < a.Length; i++)
{
if (a[i].Contains(q))protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/plain";
string q = Request["q"];
string[] a = new string[5];
a[0] = "Anna";
a[1] = "Bnna";
a[2] = "cnna";
a[3] = "dnna";
a[4] = "enna";
for (int i = 0; i < a.Length; i++)
{
if (a[i].Contains(q))
{
Response.Write(a[i] + " ");
break;
}
}
}
這里還有好多需要優化的地方,這里只是表示下使用的方式……其實這里把創建.aspx文件改成一般處理程序可能會更好一些……
3.2 Ajax 數據庫(AJAX 數據庫實例)
例子:
Test04SQL.htm
<html>
<head>
<script type="text/javascript">
function showCustomer(str) {
var xmlhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "test04getcustomer.aspx?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="" style="margin-top:15px;">
<label>請選擇章節:
<select name="customers" onchange="showCustomer(this.value)" style="font-family:Verdana, Arial, Helvetica, sans-serif;">
<option value="APPLE">請選擇</option>
<option value="APPLE">第二章</option>
</select>
</label>
</form>
<br />
<div id="txtHint">章節顯示處...</div>
</body>
</html>
test04sql.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/plain";
string q = Request["q"];
string sql = "select * from TestEssay";
DataSet ds = DbHelperSQL.Query(sql);
for (int i = 0; i < ds.Tables[0].Rows.Count;i++ )
{
Response.Write(ds.Tables[0].Rows[i]["Content"]);
}
}
此處只是隨便從數據庫讀取一些信息出來,只是介紹下操作數據庫的方式,此實例并沒有什么實際用途。
3.3 AJAX XML 實例
可參照第二章,響應……
第四章: Ajax 實例
Test05Ex.htm
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url) {
xmlhttp = null;
if (window.XMLHttpRequest) {// code for IE7, Firefox, Mozilla, etc.
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {// code for IE5, IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp != null) {
xmlhttp.onreadystatechange = onResponse;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
else {
alert("Your browser does not support XMLHTTP.");
}
}
function onResponse() {
if (xmlhttp.readyState != 4) return;
if (xmlhttp.status != 200) {
alert("Problem retrieving XML data");
return;
}
txt = "<table border='1'>";
x = xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
for (i = 0; i < x.length; i++) {
txt = txt + "<tr>";
xx = x[i].getElementsByTagName("TITLE");
{
try {
txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er) {
txt = txt + "<td> </td>";
}
}
xx = x[i].getElementsByTagName("ARTIST");
{
try {
txt = txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er) {
txt = txt + "<td> </td>";
}
}
txt = txt + "</tr>";
}
txt = txt + "</table>";
document.getElementById('copy').innerHTML = txt;
}
</script>
</head>
<body>
<div id="copy">
<button onclick="loadXMLDoc('test05.xml')">Get CD info</button>
</div>
</body>
</html>
test05.xml
<?xml version="1.0" encoding="utf-8" ?>
<CDS>
<CD>
<TITLE> hhhh </TITLE>
<ARTIST>aaa</ARTIST>
</CD>
<CD>
<TITLE> hhhh </TITLE>
<ARTIST>aaa</ARTIST>
</CD>
<CD>
<TITLE> hhhh </TITLE>
<ARTIST>aaa</ARTIST>
</CD>
<CD>
<TITLE> hhhh </TITLE>
<ARTIST>aaa</ARTIST>
</CD>
<CD>
<TITLE> hhhh </TITLE>
<ARTIST>aaa</ARTIST>
</CD>
</CDS>