首先我们需要了解XmlHttpRequest对象使用的基本步骤:
源码下载
1.创建XMLHttpRequest对象
2.创建HTTP请求
3.设置状态改变时的事件
4.发送HTTP请求
5.获取异步返回的数据
一、GetSystemTime.htm 页面如下:
代码:
<body>
<p>
使用<span>XmlHttpRequest</span>对象调用<span>Web Services</span>,并使用<span>XML DOM</span>
对象解析返回,兼容IE 和 FireFox浏览器
</p>
<div style="padding-right: 20px;">
<select id="select">
<option selected="selected" value="0">HTTP GET</option>
<option value="1">HTTP POST</option>
<option value="2">SOAP 1.1</option>
<option value="3">SOAP 1.2</option>
</select>
<input type="button" onclick="GetTime();" value="调用Web Service" />
<input type="button" value="刷新界面" onclick="RenovatePage();" />
<span style="margin-left: 40px;"><span style="color: Blue;">系统时间为:</span>
<input type="text" id="serverTime" style="background-color: #FFF9c4;" /></span>
<div id="loading" style="display: none;">
<img alt="load" src="images/loading.gif" style="float: left; padding: 0 10px 0 0;" />
<span style="color: #A11111">正在加载数据</span>
</div>
</div>
<br />
<textarea id="response" style=" 750px; height: 150px; font-family: Courier New;
background-color: #FFF9c4; font-size: 14px; margin-top: 0px;" cols="25" rows="10"></textarea><br />
</body>
二、调用页面的Js代码:
1var XHR;
2var getMode; //调用WebServices方式
3var xmlString; // 传入Xml字符串类型
4var ctype = null;
5var soapheader = null;
6var data = null;
7var newDom = null;
8var res = null;
9
10//创建xmlHttpRequest对象
11function CreatXHR() {
12 try {
13 //适用于IE5.0 或IE6.0
14 XHR = new ActiveXObject("Msxml2.XMLHTTP");
15 }
16 catch (e) {
17 try {
18 //用于IE5.0下
19 XHR = new ActiveXObject("Microsoft.XMLHTTP");
20 }
21 catch (e) {
22 XHR = false;
23 }
24 }
25 if (!XHR && typeof (XMLHttpRequest) != "undefined") {
26 //适用于IE7.0或FireFox
27 XHR = new XMLHttpRequest();
28 }
29}
1//调用函数
2function onReadyStateChange() {
3 var res = null;
4 if (XHR.readyState == 4) {
5 if (XHR.status == 200) {
6 document.getElementById("response").value = "这是返回的响应正文:\r\n" + XHR.responseText;
7 //调用XML DOM函数使用xpath及命名空间映射实现数据查询
8 res = HandleResponseByXMLDOM(XHR.responseText, data, nsMap);
9 }
10 document.getElementById("serverTime").value = res;
11 }
12}
13//根据页面单选框的选项调用Webservice
14function GetTime() {
15 getMode = document.getElementById("select").value; //从单选框中获取调用服务类型
16 InvokeWebService(getMode, "Service.asmx", "http://www.SouBao.com", "GetTime"); //调用webservice服务
17}
1/*---------------------------------------------------------------
2调用Webservice服务
3mode:指调用服务的类型[get,post,soap1.1,soap1.2]
4url:指调用webservice的文件地址
5nspace: Services的namespace,默认为null
6MethodName:webservice的方法名
7-----------------------------------------------------------------*/
8function InvokeWebService(mode, url, nspace, MethodName) {
9
10 var method = "POST"; //调用方法
11 //调用之前显示动画
12 document.getElementById("loading").style.display = "none";
13 switch (mode) {
14 // GET
15 case "0":
16 method = "GET";
17 //由于缓存的原因,用了个取巧的办法:使用一个时间戳 ['不是原创~!']
18 url = url + "/" + MethodName + "?" + new Date();
19 break;
20 // POST
21 case "1":
22 url = url + "/" + MethodName;
23 break;
24 //SOAP 1.1
25 case "2":
26 //设置Content-Type报头
27 ctype = "text/xml; charset=utf-8";
28 //设置SOAPAction报头
29 soapheader = nspace + "/" + MethodName;
30 url = url + "?.tmp=" + new Date() + "/" + MethodName;
31
32 data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
33 data += "\r\n" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
34 data += "\r\n" + "<soap:Body>"
35 data += "\r\n" + "<" + MethodName + " xmlns=\"" + nspace + "\" />";
36 data += "\r\n" + "</soap:Body>";
37 data += "\r\n" + "</soap:Envelope>";
38 break;
39 //SOAP 1.2
40 case "3":
41 ctype = "application/soap+xml; charset=utf-8";
42 //构建最终请求的url地址
43 url = url + "?.tmp=" + new Date() + "/" + MethodName;
44 data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
45 data += "\r\n" + "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">";
46 data += "\r\n" + "<soap12:Body>"
47 data += "\r\n" + "<" + MethodName + " xmlns=\"" + nspace + "\" />";
48 data += "\r\n" + "</soap12:Body>";
49 data += "\r\n" + "</soap12:Envelope>";
50 break;
51 }
52 //显示加载
53 document.getElementById("loading").style.display = "block";
54 //调用Web Services
55 //Load(method, url, onReadyStateChange, data, ctype, soapheader);
56 document.getElementById("response").value = "";
57 //延时1S
58 setTimeout(function() { Load(method, url, onReadyStateChange, data, ctype, soapheader); }, 1000);
59}
1function Load(method, url, onReadyStateChange, data, ctype, soapheader) {
2 if (ctype == null) {
3 ctype = "application/x-www-form-urlencoded; charset=utf-8";
4 }
5 //创建XMLHttpRequest对象
6 CreatXHR();
7 //创建HTTP请求
8 XHR.open(method, url, true);
9 XHR.setRequestHeader("Content-Type", ctype);
10 if (soapheader != null) {
11 XHR.setRequestHeader("SOAPAction", soapheader);
12 }
13 XHR.onreadystatechange = onReadyStateChange;
14 XHR.send(data);
15}
16
17//调用函数
18function onReadyStateChange() {
19
20 if (XHR.readyState == 4) {
21 document.getElementById("loading").style.display = "none";
22 if (XHR.status == 200) {
23 document.getElementById("response").value = "这是返回的响应正文:\r\n" + XHR.responseText;
24 //alert(XHR.responseText);
25 res = XMLDOM(XHR.responseText);
26 }
27 document.getElementById("serverTime").value = res;
28 }
29}
30
1//创建XmlDom对象
2function CreatXmlDoom(xmlString) {
3 //判断是否为IE浏览器 (IE不支持DOMparser对象)
4 if (!window.DOMParser) {
5 var progIDs = ["Msxml2.DOMDocument.3.0", "Msxml2.DOMDocument"];
6 for (var i = 0; i < progIDs.length; i++) {
7 try {
8 var xmlDOM = new ActiveXObject(progIDs[i]);
9 xmlDOM.async = false;
10 xmlDOM.setProperty("SelectionLanguage", "XPath");
11 xmlDOM.loadXML(xmlString);
12 return xmlDOM;
13 }
14 catch (ex) {
15 alert(ex);
16 }
17 }
18 return null;
19 }
20 else {
21 try {
22 var domParser = new DOMParser();
23 newDom = domParser.parseFromString(xmlString, "text/xml");
24 //alert(newDom.childNodes.length);
25 return newDom;
26
27 }
28 catch (ex) {
29 alert(ex);
30 }
31 }
32}
33//定义了一个FireFox 找到节点
34function FFParser() {
35 try {
36 var domParser = new DOMParser();
37 var newDom = domParser.parseFromString(xmlString, "text/xml");
38 // alert(newDom.childNodes.length);
39 return newDom;
40
41 }
42 catch (ex) {
43 alert(ex);
44 }
45}
1//传入XML字符串
2
3function XMLDOM(responseString) {
4 //传入xml字符串,生成XML DOM对象
5 var oXmlDom = CreatXmlDoom(responseString);
6 //若是IE浏览器 “ typeof(DOMParser)=="undefined"”这里也无法使用咯 也可以使用doucment.all
7 if (!window.DOMParser) {
8 oXmlDom.setProperty("SelectionNamespaces", "xmlns:a=\"http://www.SouBao.com\"");
9 try {
10 //执行Xpath查询
11 if (getMode < 2) {
12 // var oResults = oXmlDom.getElementsByTagName("string");
13 var oResults = oXmlDom.selectNodes("/a:string");
14 }
15 //在这个地方无法selectNodes 找到节点 很奇怪咯~~! 【 命名空间的问题咯 已经解决~~~!!!】
16 // else {
17 // var oResults = oXmlDom.selectNodes("/soap:Envelope/soap:Body/GetTimeResponse/GetTimeResult");
18 //}
19 else {
20 var oResults = oXmlDom.getElementsByTagName("GetTimeResult");
21 }
22 if (oResults != null) {
23 //读出第一个结点
24 return oResults[0].childNodes[0].nodeValue;
25 }
26 }
27 catch (ex) {
28 alert(ex);
29 return null;
30 }
31 }
32 else {
33 var oEval = new XPathEvaluator();
34 var xpath = null;
35
36 try {
37 if (getMode < 2) {
38 xpath = "/a:string";
39 }
40 else {
41 xpath = "/soap:Envelope/soap:Body/a:GetTimeResponse/GetTimeResult";
42 }
43
44 //同步
45 // XmlDoc.async = false;
46 //XmlDoc.load(responseString);
47 var oEvaluator = new XPathEvaluator();
48 var oResults = oEvaluator.evaluate(xpath, newDom, nsResolver, XPathResult.ANY_TYPE, null);
49 //alert(oResults);
50 //若结果不为空
51 if (oResults != null) {
52 var onode = oResults.iterateNext();
53
54 // while (onode != null) {
55 //alert(onode.childNodes[0].nodeValue);
56 return onode.childNodes[0].nodeValue;
57 //document.getElementById("serverTime").value = res;
58 // document.getElementById("loading").style.display = "none";
59
60 //在结果集合中选择下一节点
61 // onode = oResults.iterateNext();
62 // }
63 }
64 }
65
66 catch (ex) {
67
68 }
69 }
70 //return null;
71}
72
73//命名空间映射函数
74function nsResolver(prefix) {
75 var ns =
76 {
77 "a": "http://www.SouBao.com",
78 "b": "http://ccniit.com"
79 };
80 return ns[prefix] || null;
81}
82// 刷新界面
83function RenovatePage() {
84
85
86 window.location.reload(); //刷新操作
87 // 这个只是针对FireFox浏览器
88 document.getElementById("response").value = "";
89 document.getElementById("serverTime").value = "";
90
91
92}
三、调用Web Services 服务:
1/// <summary>
2///Service 的摘要说明
3/// </summary>
4[WebService(Namespace = "http://www.SouBao.com")]
5[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
6public class Service : System.Web.Services.WebService {
7
8 public Service () {
9
10 //如果使用设计的组件,请取消注释以下行
11 //InitializeComponent();
12 }
13
14 [WebMethod]
15 public string GetTime()
16 {
17 return DateTime.Now.ToString();
18 }
19
20}