最简单最实用的ajax(一)基础通用ajax <转>
最简单最实用的ajax(一)基础通用ajax
最通用的ajax实现整理,不调用jquery,asp.net ajax等框架,最原始ajax实现,兼容IE,FireFox。
三种最常用的数据格式(字符串、XML、JSON)的ajax实现。
提纲:
一.AJAX 概述
二.建立xmlHTTPRequest对象
三.AJAX 异步获取字符串
四.AJAX 处理xml格式数据
(1)服务器端返回xml
(2)客户端接收xml并通过javascript处理xml
五.AJAX 处理json格式数据
(1)服务器端返回json字符串
(2)客户端接收数据并通过javascript处理json字符串
一.AJAX 概述
AJAX全称:AJAX全称为“Asynchronous JavaScript and XML”(异步JavaScript和XML)
Ajax的原理:简单来说通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面。
二.建立并使用xmlHTTPRequest对象
如果有,直接返回window.XMLHttpRequest对象(IE7,IE8,FireFox);
如果没有,实用ActiveX的方式构造xmlHTTPRequest对象(IE6?)(ps:我本地试了下,好像也是直接返回XMLHttpRequest对象)。
这样就得到了一个XMLHttpRequest对象。
根据参数决定在xmlHTTPRequest的onreadystatechange事件被触发以后调用哪个回调函数。
看一下XMLHttpResponse.aspx页面里做了什么事情。
三.AJAX 异步获取字符串
服务器端返回字符串的代码
客户端获取并处理字符串
四.AJAX 处理xml格式数据
(1)服务器端返回xml
服务器端构建xml数据的两种方式:
第一种:通过System.IO命名空间下的StringWriter对象和System.Xml命名空间下的XmlTextWriter对象
FireFox和IE对XML格式数据的函数有所不同,所以在对xml进行处理之前需要先判断浏览器类型,先定义一个判断
浏览器类型的函数。
值得注意FireFox和IE对xml对象处理的不同。
selectSingleNode("")、hasChild()等函数在FireFox下是无效的。(ps:这个问题卡了我N久,郁闷!)
五.AJAX 处理json格式数据
(1)服务器端返回json字符串
(2)客户端接收数据并通过javascript处理json字符串
原文地址:http://www.cnblogs.com/candle/archive/2009/08/09/common_ajax.html
三种最常用的数据格式(字符串、XML、JSON)的ajax实现。
提纲:
一.AJAX 概述
二.建立xmlHTTPRequest对象
三.AJAX 异步获取字符串
四.AJAX 处理xml格式数据
(1)服务器端返回xml
(2)客户端接收xml并通过javascript处理xml
五.AJAX 处理json格式数据
(1)服务器端返回json字符串
(2)客户端接收数据并通过javascript处理json字符串
一.AJAX 概述
AJAX全称:AJAX全称为“Asynchronous JavaScript and XML”(异步JavaScript和XML)
Ajax的原理:简单来说通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面。
二.建立并使用xmlHTTPRequest对象
1function getXMLHttpRequest()
2 {
3 if(window.XMLHttpRequest)
4 {
5 return new window.XMLHttpRequest();
6 }
7 else
8 {
9 var progIDs = ['Msxml2.XMLHTTP','Microsoft.XMLHTTP'];
10 for(var i = 0; i < progIDs.length; i++)
11 {
12 try
13 {
14 var xmlHttp = new ActiveXObject(progIDs[i]);
15 return xmlHttp;
16 }
17 catch (ex) {}
18 }
19 return null;
20 }
21 }
先判断浏览器是否有原生的xmlHTTPRequest对象。2 {
3 if(window.XMLHttpRequest)
4 {
5 return new window.XMLHttpRequest();
6 }
7 else
8 {
9 var progIDs = ['Msxml2.XMLHTTP','Microsoft.XMLHTTP'];
10 for(var i = 0; i < progIDs.length; i++)
11 {
12 try
13 {
14 var xmlHttp = new ActiveXObject(progIDs[i]);
15 return xmlHttp;
16 }
17 catch (ex) {}
18 }
19 return null;
20 }
21 }
如果有,直接返回window.XMLHttpRequest对象(IE7,IE8,FireFox);
如果没有,实用ActiveX的方式构造xmlHTTPRequest对象(IE6?)(ps:我本地试了下,好像也是直接返回XMLHttpRequest对象)。
这样就得到了一个XMLHttpRequest对象。
1function sendRequest(action)
2 {
3 var xhr = getXMLHttpRequest();
4 xhr.open("POST","XMLHttpResponse.aspx?act="+action)
5 if (action == "string")
6 {
7 xhr.onreadystatechange = function()
8 {
9 getString.apply(xhr);
10 }
11 }
12 else if (action == "xml")
13 {
14 xhr.onreadystatechange = function()
15 {
16 getXml.apply(xhr);
17 }
18 }
19 else if (action == "json")
20 {
21 xhr.onreadystatechange = function()
22 {
23 getJson.apply(xhr);
24 }
25 }
26 xhr.send(null);
27 }
通过传参给服务器端,来决定服务器端返回的数据类型。2 {
3 var xhr = getXMLHttpRequest();
4 xhr.open("POST","XMLHttpResponse.aspx?act="+action)
5 if (action == "string")
6 {
7 xhr.onreadystatechange = function()
8 {
9 getString.apply(xhr);
10 }
11 }
12 else if (action == "xml")
13 {
14 xhr.onreadystatechange = function()
15 {
16 getXml.apply(xhr);
17 }
18 }
19 else if (action == "json")
20 {
21 xhr.onreadystatechange = function()
22 {
23 getJson.apply(xhr);
24 }
25 }
26 xhr.send(null);
27 }
根据参数决定在xmlHTTPRequest的onreadystatechange事件被触发以后调用哪个回调函数。
看一下XMLHttpResponse.aspx页面里做了什么事情。
1protected void Page_Load(object sender, EventArgs e)
2 {
3 if (this.Request.QueryString["act"] != null && this.Request.QueryString["act"].ToString().Trim().Length > 0)
4 {
5 string action = this.Request.QueryString["act"].ToString().Trim();
6 if (action == "string")
7 {
8 this.ResponseString(); //返回文本字符串
9 }
10 else if (action == "xml")
11 {
12 this.ResponseXML(); //返回xml文本
13 }
14 else if (action == "json")
15 {
16 this.ResponseJSON(); //返回json字符串
17 }
18 }
19 }
2 {
3 if (this.Request.QueryString["act"] != null && this.Request.QueryString["act"].ToString().Trim().Length > 0)
4 {
5 string action = this.Request.QueryString["act"].ToString().Trim();
6 if (action == "string")
7 {
8 this.ResponseString(); //返回文本字符串
9 }
10 else if (action == "xml")
11 {
12 this.ResponseXML(); //返回xml文本
13 }
14 else if (action == "json")
15 {
16 this.ResponseJSON(); //返回json字符串
17 }
18 }
19 }
三.AJAX 异步获取字符串
服务器端返回字符串的代码
1protected void ResponseString()
2 {
3 Response.Write("Return a string from server.");
4 Response.End();
5 }
2 {
3 Response.Write("Return a string from server.");
4 Response.End();
5 }
客户端获取并处理字符串
1function getString()
2 {
3 if (this.readyState == 4)
4 {
5 if(this.status == 200)
6 {
7 var strtest = this.responseText;
8 var showDIV = document.getElementById("showHTML");
9 showDIV.innerHTML = "<ul><li>"+strtest+"</li></ul>";
10 showDIV.style.background = "#EE6600";
11 }
12 else
13 {
14 throw new Error();
15 }
16 }
17 }
this及上文建立的xmlHTTPRequest对象。2 {
3 if (this.readyState == 4)
4 {
5 if(this.status == 200)
6 {
7 var strtest = this.responseText;
8 var showDIV = document.getElementById("showHTML");
9 showDIV.innerHTML = "<ul><li>"+strtest+"</li></ul>";
10 showDIV.style.background = "#EE6600";
11 }
12 else
13 {
14 throw new Error();
15 }
16 }
17 }
四.AJAX 处理xml格式数据
(1)服务器端返回xml
服务器端构建xml数据的两种方式:
第一种:通过System.IO命名空间下的StringWriter对象和System.Xml命名空间下的XmlTextWriter对象
1protected void ResponseXML()
2 {
3 StringWriter sw = new StringWriter();
4 XmlTextWriter xtw = new XmlTextWriter(sw);
5 xtw.WriteStartDocument();
6 xtw.WriteStartElement("Person");
7
8 //Name节点
9 xtw.WriteStartElement("Name");
10 xtw.WriteString("Candle");
11 xtw.WriteEndElement();
12 //Age节点
13 xtw.WriteStartElement("Age");
14 xtw.WriteString("254");
15 xtw.WriteEndElement();
16 //Job节点
17 xtw.WriteStartElement("Job");
18 xtw.WriteString("Software Engineer");
19 xtw.WriteEndElement();
20
21 xtw.WriteEndElement();
22 xtw.WriteEndDocument();
23 string xmlstr = sw.ToString().Replace("utf-8", "gb2312").Replace("utf-16", "gb2312");
24 Response.ContentType = "text/xml";
25 Response.Charset = "GB2312";
26 Response.Write(xmlstr);
27 Response.End();
28 }
第二种:直接拼接字符串2 {
3 StringWriter sw = new StringWriter();
4 XmlTextWriter xtw = new XmlTextWriter(sw);
5 xtw.WriteStartDocument();
6 xtw.WriteStartElement("Person");
7
8 //Name节点
9 xtw.WriteStartElement("Name");
10 xtw.WriteString("Candle");
11 xtw.WriteEndElement();
12 //Age节点
13 xtw.WriteStartElement("Age");
14 xtw.WriteString("254");
15 xtw.WriteEndElement();
16 //Job节点
17 xtw.WriteStartElement("Job");
18 xtw.WriteString("Software Engineer");
19 xtw.WriteEndElement();
20
21 xtw.WriteEndElement();
22 xtw.WriteEndDocument();
23 string xmlstr = sw.ToString().Replace("utf-8", "gb2312").Replace("utf-16", "gb2312");
24 Response.ContentType = "text/xml";
25 Response.Charset = "GB2312";
26 Response.Write(xmlstr);
27 Response.End();
28 }
1protected void ResponseXML()
2 {
3 string xmlstr = @"<?xml version='1.0' encoding='gb2312' ?>
4 <Persons>
5 <Person>
6 <Name>
7 <Firstname>Candle</Firstname>
8 <Lastname>Zhu</Lastname>
9 </Name>
10 <Age>25</Age>
11 <Job>Software Engineer</Job>
12 <Salary>10000</Salary>
13 </Person>
14 <Person>
15 <Name>
16 <Firstname>Kevin</Firstname>
17 <Lastname>Zhu</Lastname>
18 </Name>
19 <Age>30</Age>
20 <Job>UI Designer</Job>
21 <Salary>10000</Salary>
22 </Person>
23 </Persons>";
24
25 Response.ContentType = "text/xml";
26 Response.Charset = "GB2312";
27 Response.Write(xmlstr);
28 Response.End();
29 }
(2)客户端接收xml并使用javascript处理xml2 {
3 string xmlstr = @"<?xml version='1.0' encoding='gb2312' ?>
4 <Persons>
5 <Person>
6 <Name>
7 <Firstname>Candle</Firstname>
8 <Lastname>Zhu</Lastname>
9 </Name>
10 <Age>25</Age>
11 <Job>Software Engineer</Job>
12 <Salary>10000</Salary>
13 </Person>
14 <Person>
15 <Name>
16 <Firstname>Kevin</Firstname>
17 <Lastname>Zhu</Lastname>
18 </Name>
19 <Age>30</Age>
20 <Job>UI Designer</Job>
21 <Salary>10000</Salary>
22 </Person>
23 </Persons>";
24
25 Response.ContentType = "text/xml";
26 Response.Charset = "GB2312";
27 Response.Write(xmlstr);
28 Response.End();
29 }
FireFox和IE对XML格式数据的函数有所不同,所以在对xml进行处理之前需要先判断浏览器类型,先定义一个判断
浏览器类型的函数。
1function getOs()
2 {
3 var OsObject = "";
4 if(navigator.userAgent.indexOf("MSIE")>0)
5 {
6 return "MSIE";
7 }
8 if(isFirefox=navigator.userAgent.indexOf("Firefox")>0)
9 {
10 return "Firefox";
11 }
12 if(isSafari=navigator.userAgent.indexOf("Safari")>0)
13 {
14 return "Safari";
15 }
16 if(isCamino=navigator.userAgent.indexOf("Camino")>0)
17 {
18 return "Camino";
19 }
20 if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0)
21 {
22 return "Gecko";
23 }
24 }
下面就是通过客户端获得并处理xml的函数了。2 {
3 var OsObject = "";
4 if(navigator.userAgent.indexOf("MSIE")>0)
5 {
6 return "MSIE";
7 }
8 if(isFirefox=navigator.userAgent.indexOf("Firefox")>0)
9 {
10 return "Firefox";
11 }
12 if(isSafari=navigator.userAgent.indexOf("Safari")>0)
13 {
14 return "Safari";
15 }
16 if(isCamino=navigator.userAgent.indexOf("Camino")>0)
17 {
18 return "Camino";
19 }
20 if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0)
21 {
22 return "Gecko";
23 }
24 }
1function getXml()
2 {
3 var osObject = getOs();
4 var strHTML = "";
5 var xmlDoc = null;
6 var Firstname = "";
7 var Lastname = "";
8 var Age = "";
9 var Job = "";
10 var Salary = "";
11 if (this.readyState == 4)
12 {
13 if(this.status == 200)
14 {
15 var xmlDoc = this.responseXML;
16 var xmlPersons = xmlDoc.getElementsByTagName("Person");
17 for(var i = 0 ; i<xmlPersons.length; i++)
18 {
19 var person = xmlPersons[i];
20 if (osObject == "MSIE")
21 {
22 Firstname = person.getElementsByTagName("Firstname")[0].text;
23 Lastname = person.getElementsByTagName("Lastname")[0].text;
24 Age = person.getElementsByTagName("Age")[0].text;
25 Job = person.getElementsByTagName("Job")[0].text;
26 Salary = person.getElementsByTagName("Salary")[0].text;
27 }
28 else
29 {
30 Firstname = person.getElementsByTagName("Firstname")[0].textContent;
31 Lastname = person.getElementsByTagName("Lastname")[0].textContent;
32 Age = person.getElementsByTagName("Age")[0].textContent;
33 Job = person.getElementsByTagName("Job")[0].textContent;
34 Salary = person.getElementsByTagName("Salary")[0].textContent;
35 }
36 strHTML += "<ul>";
37 strHTML += "<li>" + Firstname + Lastname + "</li>";
38 strHTML += "<li>" + Age + "</li>";
39 strHTML += "<li>" + Job + "</li>";
40 strHTML += "<li>" + Salary + "</li>";
41 strHTML += "</ul>";
42 }
43 var showDIV = document.getElementById("showHTML");
44 showDIV.innerHTML = strHTML;
45 showDIV.style.background = "#CCCCCC";
46 }
47 else
48 {
49 throw new Error();
50 }
51 }
52 }
通过var xmlDoc = this.responseXML就可以获得服务器端返回的xml数据并得到一个xml文本对象了。2 {
3 var osObject = getOs();
4 var strHTML = "";
5 var xmlDoc = null;
6 var Firstname = "";
7 var Lastname = "";
8 var Age = "";
9 var Job = "";
10 var Salary = "";
11 if (this.readyState == 4)
12 {
13 if(this.status == 200)
14 {
15 var xmlDoc = this.responseXML;
16 var xmlPersons = xmlDoc.getElementsByTagName("Person");
17 for(var i = 0 ; i<xmlPersons.length; i++)
18 {
19 var person = xmlPersons[i];
20 if (osObject == "MSIE")
21 {
22 Firstname = person.getElementsByTagName("Firstname")[0].text;
23 Lastname = person.getElementsByTagName("Lastname")[0].text;
24 Age = person.getElementsByTagName("Age")[0].text;
25 Job = person.getElementsByTagName("Job")[0].text;
26 Salary = person.getElementsByTagName("Salary")[0].text;
27 }
28 else
29 {
30 Firstname = person.getElementsByTagName("Firstname")[0].textContent;
31 Lastname = person.getElementsByTagName("Lastname")[0].textContent;
32 Age = person.getElementsByTagName("Age")[0].textContent;
33 Job = person.getElementsByTagName("Job")[0].textContent;
34 Salary = person.getElementsByTagName("Salary")[0].textContent;
35 }
36 strHTML += "<ul>";
37 strHTML += "<li>" + Firstname + Lastname + "</li>";
38 strHTML += "<li>" + Age + "</li>";
39 strHTML += "<li>" + Job + "</li>";
40 strHTML += "<li>" + Salary + "</li>";
41 strHTML += "</ul>";
42 }
43 var showDIV = document.getElementById("showHTML");
44 showDIV.innerHTML = strHTML;
45 showDIV.style.background = "#CCCCCC";
46 }
47 else
48 {
49 throw new Error();
50 }
51 }
52 }
值得注意FireFox和IE对xml对象处理的不同。
selectSingleNode("")、hasChild()等函数在FireFox下是无效的。(ps:这个问题卡了我N久,郁闷!)
五.AJAX 处理json格式数据
(1)服务器端返回json字符串
1protected void ResponseJSON()
2 {
3 //StringBuilder sb = new StringBuilder();
4 //sb.Append("{\"persons\":[");
5 //sb.Append("{\"Firstname\":\"Candle\",\"Lastname\":\"Zhu\",\"Age\":25,\"Job\":\"Software Engineer\",\"Salary\":10000},");
6 //sb.Append("{\"Firstname\":\"Kevin\",\"Lastname\":\"Zhu\",\"Age\":25,\"Job\":\"UI Designer\",\"Salary\":10000}");
7 //sb.Append("]}");
8
9 string jsonStr = @"{'persons':[
10 {'Firstname':'Candle','Lastname':'Zhu','Age':25,'Job':'Software Engineer','Salary':10000},
11 {'Firstname':'Kevin','Lastname':'Zhu','Age':25,'Job':'UI Designer','Salary':10000}
12 ]}";
13 Response.Write(jsonStr);
14 Response.End();
15 }
json字符串可以在服务器端直接拼接即可2 {
3 //StringBuilder sb = new StringBuilder();
4 //sb.Append("{\"persons\":[");
5 //sb.Append("{\"Firstname\":\"Candle\",\"Lastname\":\"Zhu\",\"Age\":25,\"Job\":\"Software Engineer\",\"Salary\":10000},");
6 //sb.Append("{\"Firstname\":\"Kevin\",\"Lastname\":\"Zhu\",\"Age\":25,\"Job\":\"UI Designer\",\"Salary\":10000}");
7 //sb.Append("]}");
8
9 string jsonStr = @"{'persons':[
10 {'Firstname':'Candle','Lastname':'Zhu','Age':25,'Job':'Software Engineer','Salary':10000},
11 {'Firstname':'Kevin','Lastname':'Zhu','Age':25,'Job':'UI Designer','Salary':10000}
12 ]}";
13 Response.Write(jsonStr);
14 Response.End();
15 }
(2)客户端接收数据并通过javascript处理json字符串
1function getJson()
2 {
3 var strHTML = "";
4 var Firstname = "";
5 var Lastname = "";
6 var Age = "";
7 var Job = "";
8 var Salary = "";
9 if (this.readyState == 4)
10 {
11 if(this.status == 200)
12 {
13 var jsonStr = this.responseText;
14 var json = eval("("+jsonStr+")");
15 for (var i=0 ; i < json.persons.length; i++)
16 {
17 Firstname = json.persons[i].Firstname;
18 Lastname = json.persons[i].Lastname;
19 Age = json.persons[i].Age;
20 Job = json.persons[i].Job;
21 Salary = json.persons[i].Salary;
22 strHTML += "<ul>";
23 strHTML += "<li>" + Firstname + Lastname + "</li>";
24 strHTML += "<li>" + Age + "</li>";
25 strHTML += "<li>" + Job + "</li>";
26 strHTML += "<li>" + Salary + "</li>";
27 strHTML += "</ul>";
28 }
29 var showDIV = document.getElementById("showHTML");
30 showDIV.innerHTML = strHTML;
31 showDIV.style.background = "#00ff00";
32 }
33 else
34 {
35 throw new Error();
36 }
37 }
38 }
可以看出在客户端处理json字符串要比处理xml方便很多,所以我觉得能用json的地方尽量用json吧!2 {
3 var strHTML = "";
4 var Firstname = "";
5 var Lastname = "";
6 var Age = "";
7 var Job = "";
8 var Salary = "";
9 if (this.readyState == 4)
10 {
11 if(this.status == 200)
12 {
13 var jsonStr = this.responseText;
14 var json = eval("("+jsonStr+")");
15 for (var i=0 ; i < json.persons.length; i++)
16 {
17 Firstname = json.persons[i].Firstname;
18 Lastname = json.persons[i].Lastname;
19 Age = json.persons[i].Age;
20 Job = json.persons[i].Job;
21 Salary = json.persons[i].Salary;
22 strHTML += "<ul>";
23 strHTML += "<li>" + Firstname + Lastname + "</li>";
24 strHTML += "<li>" + Age + "</li>";
25 strHTML += "<li>" + Job + "</li>";
26 strHTML += "<li>" + Salary + "</li>";
27 strHTML += "</ul>";
28 }
29 var showDIV = document.getElementById("showHTML");
30 showDIV.innerHTML = strHTML;
31 showDIV.style.background = "#00ff00";
32 }
33 else
34 {
35 throw new Error();
36 }
37 }
38 }
原文地址:http://www.cnblogs.com/candle/archive/2009/08/09/common_ajax.html