介绍

AJAX 不是一种新的编程语言,而是创建快速和动态页面的技术。有了它,你可以实现

  • 在不重载页面的情况下更新内容
  • 向服务器请求数据
  • 从服务器下载数据
  • 后台运行发送数据给服务器

定义

AJAX = Asynchronous JavaScript and XML,直接翻译是异步的 JavaScript 和 XML,这其实有误导的嫌疑,即使不懂 XML 也可以使用 AJAX。

应用

使用 AJAX 技术的应用有:Google Maps, Gmail, Youtube, Facebook etc.

AJAX 工作流程

ajax

AJAX 基于标准的互联网协议

AJAX 基于互联网协议,主要是下面两种

  • XMLHttpRequest object (to retrieve data from a web server)
  • JavaScript/DOM (to display/use the data)

AJAX 2005 年因为 Google Suggest 开始流行。当你在搜索框里输入时,JavaScript 就已经开始发送数据到服务器,服务器根据输入返回一个建议列表。

XMLHttpRequest object

XMLHttpRequest object 是 AJAX 是基础。所有现代的浏览器都支持 XMLHttpRequest object,用它来跟服务器交换数据。

创建 XMLHttpRequest object
xhr = new XMLHttpRequest();

AJAX 发送请求

我们使用 XMLHttpRequest 对象的 open() 和 send() 方法来发送请求:

GET

1
2
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

POST

1
2
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();

get-post

加上头信息

1
2
3
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

setRequestHeader

上面定义清晰的说明了 AJAX 是异步的,所以 open() 的第三个参数指定为 true。能异步执行,对开发者来说实在是一件大好事,我们都知道服务端执行程序一般都非常耗时,在没有 AJAX 之前许多操作都有可能导致服务端挂起或者停止。有了 AJAX 之后,JavaScript 再有不用一直等待服务端的响应了

  • 可以在等待服务端响应的时候同时执行脚本
  • 可以在响应准备好时,开始处理响应。
1
2
3
4
5
6
7
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

服务端响应

XMLHttpRequest 对象的 responseText(as String) 和 responseXML(as XML) 属性可以获取服务端响应。

responseText

1
2
服务端直接响应 String,可以直接使用
document.getElementById("demo").innerHTML = xhttp.responseText;

responseXML

1
2
3
4
5
6
7
8
从服务端请求 cd_catalog.xml 并且解析响应
xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;

AJAX 的 onreadystatechange 事件

你如果仔细观察的话,我们在上面已经用了一些事件。比如在响应准备好时 onreadystatechange。当请求发啊送之后,我们想基于服务端的响应执行一些动作。当每一次 readyState 改变的时候,就会触发 onreadystatechange 事件。readyState 代表了 XMLHttpRequest 的状态。下
图是 XMLHttpRequest 对象的一些重要属性
onreadystatechange
在这张图里,我们能看出当 readyState 是 4 和 status 是 200 的时候,响应就准备好了,下面用代码举个例子:

1
2
3
4
5
6
7
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};

AJAX 和 PHP 脚本的交互

下面通过输入一些字符,演示了一个 Web 页面如何跟服务端交互的,源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "gethint.php?q="+str, true);
xhttp.send();
}
</script>
</body>
</html>

PHP 文件 gethint.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;

##AJAX 和 数据库的交互
下面通过一个例子演示了 Web 页面如何通过 AJAX 从数据库获取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "getcustomer.asp?q="+str, true);
xhttp.send();
}

getcustomer.asp 从数据库中查询信息,并且返回给 HTML 页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/datafolder/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn
response.write("<table>")
do until rs.EOF
for each x in rs.Fields
response.write("<tr><td><b>" & x.name & "</b></td>")
response.write("<td>" & x.value & "</td></tr>")
next
rs.MoveNext
loop
response.write("</table>")
%>

参考文档:w3cshools