AJAX实例:XHR的入门
XHR对象的使用是 AJAX 的核心。为了学习的方便,在编写代码过程中没有用服务端开发的部分,Web前端开发与服务端开发的结合处在于“响应数据”(如XML)。 XML部分我直接写好已放在服务器了,重点不在服务端程序如何去从数据库调出相应的数据的内容。
一个很简单的示例:点击“查看”按钮,用户名(username)显示在网页中。
HTML代码:
1<label>用户名</label>
2<span>username 值</span>
3<a href="#" onclick="ajaxread('3.xml', ''); return false;">查看</a>
2<span>username 值</span>
3<a href="#" onclick="ajaxread('3.xml', ''); return false;">查看</a>
XML代码:
1<?xml version="1.0" encoding="gb2312"?>
2<root>
3 <username>
4 george wing
5 </username>
6</root>
2<root>
3 <username>
4 george wing
5 </username>
6</root>
Javascript代码:
1function ajaxread(file, postData) {
2 var req = createXMLHTTPObject();
3 if(!req) return;
4 req.onreadystatechange = function() {
5 if (req.readyState != 4) return;
6 if (req.status != 200 && req.status != 304) {
7 alert('HTTP error ' + req.status);
8 return;
9 }
10
11 updateobj('span', req.responseXML.getElementsByTagName('username')[0].firstChild.nodeValue);
12 }
13 req.open('GET', file, true);
14 req.setRequestHeader('User-Agent','XMLHTTP/1.0');
15 if (req.readyState == 4) return;
16 req.send(postData);
17}
18function updateobj(obj, data) {
19 document.getElementsByTagName(obj)[0].firstChild.nodeValue = data;
20}
21
22var XMLHttpFactories = [
23 function() {return new XMLHttpRequest()},
24 function () {return new ActiveXObject("Msxml2.XMLHTTP")},
25 function () {return new ActiveXObject("Msxml3.XMLHTTP")},
26 function () {return new ActiveXObject("Microsoft.XMLHTTP")},
27];
28
29function createXMLHTTPObject() {
30 var xmlhttp = false;
31 for(i=0; i<XMLHttpFactories.length; i++) {
32 try {
33 xmlhttp = XMLHttpFactories[i]();
34 }
35 catch(e) {
36 continue;
37 }
38 break;
39 }
40 return xmlhttp;
41}
2 var req = createXMLHTTPObject();
3 if(!req) return;
4 req.onreadystatechange = function() {
5 if (req.readyState != 4) return;
6 if (req.status != 200 && req.status != 304) {
7 alert('HTTP error ' + req.status);
8 return;
9 }
10
11 updateobj('span', req.responseXML.getElementsByTagName('username')[0].firstChild.nodeValue);
12 }
13 req.open('GET', file, true);
14 req.setRequestHeader('User-Agent','XMLHTTP/1.0');
15 if (req.readyState == 4) return;
16 req.send(postData);
17}
18function updateobj(obj, data) {
19 document.getElementsByTagName(obj)[0].firstChild.nodeValue = data;
20}
21
22var XMLHttpFactories = [
23 function() {return new XMLHttpRequest()},
24 function () {return new ActiveXObject("Msxml2.XMLHTTP")},
25 function () {return new ActiveXObject("Msxml3.XMLHTTP")},
26 function () {return new ActiveXObject("Microsoft.XMLHTTP")},
27];
28
29function createXMLHTTPObject() {
30 var xmlhttp = false;
31 for(i=0; i<XMLHttpFactories.length; i++) {
32 try {
33 xmlhttp = XMLHttpFactories[i]();
34 }
35 catch(e) {
36 continue;
37 }
38 break;
39 }
40 return xmlhttp;
41}
学会AJAX的关键是XHR对象的使用,另外还需要HTTP的知识。
(完)
AJAX 系列blog文章: