###第一章: 基础
##### 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();
```
![方法介绍](http://upload-images.jianshu.io/upload_images/2789632-22ccdb6d9cd08fba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
###### 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");
```
![setRequestHeader方法](http://upload-images.jianshu.io/upload_images/2789632-9552d39752f054a1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
** 请记住,JavaScript 会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。**
##### 2.3 XHR 响应(AJAX - 服务器响应)
2.3.1 服务器响应
如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。
![属性描述](http://upload-images.jianshu.io/upload_images/2789632-bc6b9965a30d37d5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
例子:(获取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>
```
![](http://upload-images.jianshu.io/upload_images/2789632-f3d0a3f45dd74597.gif?imageMogr2/auto-orient/strip)
##### 2.4 XML readState(AJAX - onreadystatechange 事件)
![](http://upload-images.jianshu.io/upload_images/2789632-93e2ef0628185014.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
代码:
```
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 ?
```
![点击结果](http://upload-images.jianshu.io/upload_images/2789632-0aa09d6a8daf42d9.gif?imageMogr2/auto-orient/strip)
###第三章 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;
}
}
}
```
![](http://upload-images.jianshu.io/upload_images/2789632-1bf0992d799a7bad.gif?imageMogr2/auto-orient/strip)
这里还有好多需要优化的地方,这里只是表示下使用的方式……其实这里把创建.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"]);
}
}
```
![](http://upload-images.jianshu.io/upload_images/2789632-0ce34179dddfe0f4.gif?imageMogr2/auto-orient/strip)
此处只是随便从数据库读取一些信息出来,只是介绍下操作数据库的方式,此实例并没有什么实际用途。
######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>
```
![](http://upload-images.jianshu.io/upload_images/2789632-fa5f4d84711b0a5c.gif?imageMogr2/auto-orient/strip)