XMLHttpRequest 详解与操作xml文件代码
XMLHttpRequest 详解与操作xml文件代码
什么是 XMLHttpRequest 对象?
XMLHttpRequest 对象用于在后台与服务器交换数据。
XMLHttpRequest 对象是开发者的梦想,因为您能够:
在不重新加载页面的情况下更新网页
在页面已加载后从服务器请求数据
在页面已加载后从服务器接收数据
在后台向服务器发送数据
所有现代的浏览器都支持 XMLHttpRequest 对象。
如需学习更多有关 XMLHttpRequest 对象的知识,请学习我们的 XML DOM 教程。
实例:当键入文本时与服务器进行 XML HTTP 通信。
创建 XMLHttpRequest 对象
所有现代浏览器 (IE7+、Firefox、Chrome、Safari 以及 Opera) 都内建了 XMLHttpRequest 对象。
通过一行简单的 JavaScript 代码,我们就可以创建 XMLHttpRequest 对象。
创建 XMLHttpRequest 对象的语法:
xmlhttp=new XMLHttpRequest();老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");提示:在下一章,我们将使用 XMLHttpRequest 对象从服务器取回 XML 信息。
实例 1
<script type="text/网页特效">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
// ...our code here...
}
else
{
alert("Problem retrieving XML data");
}
}
}
</script>亲自试一试
注释:onreadystatechange 是一个事件句柄。它的值 (state_Change) 是一个函数的名称,当 XMLHttpRequest 对象的状态发生改变时,会触发此函数。状态从 0 (uninitialized) 到 4 (complete) 进行变化。仅在状态为 4 时,我们才执行代码。
为什么使用 Async=true ?
我们的实例在 open() 的第三个参数中使用了 "true"。
该参数规定请求是否异步处理。
True 表示脚本会在 send() 方法之后继续执行,而不等待来自服务器的响应。
onreadystatechange 事件使代码复杂化了。但是这是在没有得到服务器响应的情况下,防止代码停止的最安全的方法。
通过把该参数设置为 "false",可以省去额外的 onreadystatechange 代码。如果在请求失败时是否执行其余的代码无关紧要,那么可以使用这个参数。
XMLHttpRequest对象采用异步方式对服务器发送Get方式的请求,访问服务器的.ashx文件,获得服务器响应后触发定义好的回调函数。
本文将会编写 XMLHttpRequest对象采用异步方式对服务器以Post的请求发方式送XML文档
本文使用环境VS2005,运行VS2005,打开现有项目,新建一个Web窗体,命名为 PostXML.asp教程x
代码如下:
view plaincopy to clipboardprint?
01.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PostXML.aspx.cs" Inherits="_PostXML" %>
02.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
03.<html xmlns="http://www.w3.org/1999/xhtml" >
04.<head runat="server">
05. <title>无标题页</title>
06. <script type="text/javascript"><!--
07. var xmlHttp=null;
08.
09. function createXMLHttpRequest()
10. {
11. if(xmlHttp == null){
12. if(window.XMLHttpRequest) {
13. //Mozilla 浏览器
14. xmlHttp = new XMLHttpRequest();
15. }else if(window.ActiveXObject) {
16. // IE浏览器
17. try {
18. xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
19. } catch (e) {
20. try {
21. xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
22. } catch (e) {
23. alert('创建失败');
24. }
25. }
26. }
27. }
28. }
29.
30. function openAjax(xml)
31. {
32. if( xmlHttp == null)
33. {
34. createXMLHttpRequest();
35. if( xmlHttp == null)
36. {
37. alert('出错');
38. return ;
39. }
40. }
41.
42. xmlHttp.open("post","Result.aspx?date="+new Date().getTime(),true);
43.
44. xmlHttp.onreadystatechange=xmlHttpChange;
45.
46. xmlHttp.send(xml);
47. }
48.
49. function xmlHttpChange()
50. {
51. if(xmlHttp.readyState==4)
52. {
53. if(xmlHttp.status==200)
54. {
55. document.getElementById('resultDiv').innerHTML=xmlHttp.responseText;
56. }
57. }
58. }
59.
60. function loadXML(xmlSrc)
61. {
62. var xmlDoc;
63. if(window.ActiveXObject)
64. {
65. xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
66. xmlDoc.async = false;
67. xmlDoc.load(xmlSrc);
68. if(xmlDoc.parseError.errorCode!=0)
69. {
70. alert("出错!"+xmlDoc.parseError.reason);
71. }
72. }
73. else if (document.implementation&&document.implementation.createDocument)
74. {
75. xmlDoc = document.implementation.createDocument('', '', null);
76. xmlDoc.async=false;
77. xmlDoc.load(xmlSrc);
78. }
79. else
80. {
81. return null;
82. }
83.
84. return xmlDoc;
85. }
86.
87. function postXML(xmlSrc)
88. {
89. var xml;
90. if(xmlSrc=='')
91. {
92. xml="<?xml version='1.0' encoding='utf-8'?><pet><type>cats</type><type>dogs</type></pet>";
93. }
94. else
95. {
96. xml=loadXML(xmlSrc);
97. }
98. if(xml==null)
99. {
100. alert('XML文档创建失败');
101. }
102. else
103. {
104. openAjax(xml);
105. }
106. }
107.
108.// --></script>
109.</head>
110.<body>
111. <form id="form1" runat="server">
112. 发送构建的XML格式字符串 <input type="button" value="发送" onclick="postXML('');" /><br />
113. 发送现有XML文档 <input type="button"value="发送" onclick="postXML('XMLFile.xml');" />
114. <div id="resultDiv"></div>
115. </form>
116.</body>
117.</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PostXML.aspx.cs" Inherits="_PostXML" %>
<!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>
<script type="text/javascript"><!--
var xmlHttp=null;
function createXMLHttpRequest()
{
if(xmlHttp == null){
if(window.XMLHttpRequest) {
//Mozilla 浏览器
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {
// IE浏览器
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('创建失败');
}
}
}
}
}
function openAjax(xml)
{
if( xmlHttp == null)
{
createXMLHttpRequest();
if( xmlHttp == null)
{
alert('出错');
return ;
}
}
xmlHttp.open("post","Result.aspx?date="+new Date().getTime(),true);
xmlHttp.onreadystatechange=xmlHttpChange;
xmlHttp.send(xml);
}
function xmlHttpChange()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
document.getElementById('resultDiv').innerHTML=xmlHttp.responseText;
}
}
}
function loadXML(xmlSrc)
{
var xmlDoc;
if(window.ActiveXObject)
{
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = false;
xmlDoc.load(xmlSrc);
if(xmlDoc.parseError.errorCode!=0)
{
alert("出错!"+xmlDoc.parseError.reason);
}
}
else if (document.implementation&&document.implementation.createDocument)
{
xmlDoc = document.implementation.createDocument('', '', null);
xmlDoc.async=false;
xmlDoc.load(xmlSrc);
}
else
{
return null;
}
return xmlDoc;
}
function postXML(xmlSrc)
{
var xml;
if(xmlSrc=='')
{
xml="<?xml version='1.0' encoding='utf-8'?><pet><type>cats</type><type>dogs</type></pet>";
}
else
{
xml=loadXML(xmlSrc);
}
if(xml==null)
{
alert('XML文档创建失败');
}
else
{
openAjax(xml);
}
}
// --></script>
</head>
<body>
<form id="form1" runat="server">
发送构建的XML格式字符串 <input type="button" value="发送" onclick="postXML('');" /><br />
发送现有XML文档 <input type="button"value="发送" onclick="postXML('XMLFile.xml');" />
<div id="resultDiv"></div>
</form>
</body>
</html>
上篇XMLHttpRequest 对象访问的是服务器.ashx文件 (一般处理程序),本文访问的是.aspx文件 (另一个Web窗体)
新建一个Web窗体 用于处理请求 命名为 Result.aspx
代码如下:
Result.aspx.cs
view plaincopy to clipboardprint?
01.using System;
02.using System.Data;
03.using System.Configuration;
04.using System.Collections;
05.using System.Web;
06.using System.Web.Security;
07.using System.Web.UI;
08.using System.Web.UI.WebControls;
09.using System.Web.UI.WebControls.WebParts;
10.using System.Web.UI.HtmlControls;
11.using System.Xml;
12.public partial class ajax_xmlHttpRequest_Result : System.Web.UI.Page
13.{
14. protected void Page_Load(object sender, EventArgs e)
15. {
16. XmlDocument xmlDoc = new XmlDocument();
17. xmlDoc.Load(Request.InputStream);
18. XmlNodeList selectedPetTypes = xmlDoc.GetElementsByTagName("type");
19. String type = null;
20. String responseText = "Selected Pets: ";
21. for (int i = 0; i < selectedPetTypes.Count; i++)
22. {
23. type = selectedPetTypes[i].FirstChild.Value;
24. responseText = responseText + " " + type;
25. }
26. Response.Write(responseText);
27. Response.End();
28. }
29.}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
public partial class ajax_xmlHttpRequest_Result : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Request.InputStream);
XmlNodeList selectedPetTypes = xmlDoc.GetElementsByTagName("type");
String type = null;
String responseText = "Selected Pets: ";
for (int i = 0; i < selectedPetTypes.Count; i++)
{
type = selectedPetTypes[i].FirstChild.Value;
responseText = responseText + " " + type;
}
Response.Write(responseText);
Response.End();
}
}
然后创建一个XML文档,命名为 XMLFile.xml
代码如下:
view plaincopy to clipboardprint?
01.<?xml version='1.0' encoding='utf-8'?>
02.<pet>
03. <type>mouse</type>
04. <type>pig</type>
05.</pet>
<?xml version='1.0' encoding='utf-8'?>
<pet>
<type>mouse</type>
<type>pig</type>
</pet>
XML / ASP
您也可以把 XML 文档打开并发送到服务器上的 ASP 页面,分析此请求,然后传回结果。
<html>
<body>
<script type="text/javascript">
xmlHttp=null;
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc.
xmlHttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp!=null)
{
xmlHttp.open("GET", "note.xml", false);
xmlHttp.send(null);
xmlDoc=xmlHttp.responseText;xmlHttp.open("POST", "demo_dom_http.asp", false);
xmlHttp.send(xmlDoc);
document.write(xmlHttp.responseText);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
</script>
</body>
</html>ASP 页面,由 VBScript 编写:<%
set xmldoc = Server.CreateObject("Microsoft.XMLDOM")
xmldoc.async=false
xmldoc.load(request)for each x in xmldoc.documentElement.childNodes
if x.NodeName = "to" then name=x.text
next
response.write(name)
%>通过使用 response.write 属性把结果传回客户端
补充:网页制作,js教程