看了部落格園和Csdn上的一些關於js調用webservice文章,感覺不錯,不過他們給的程式,有些存在或多或少的錯誤,我調試了一下,現貼出來,既能與大家分享,也能為自己的學習做一下記錄。
一,理論(省略)
二,樣本(分1,2,3)
1.webservice的編寫
查看webservice代碼
1 using System.Web;
2 using System.Web.Services;
3 using System.Web.Services.Protocols;
4 using System.Xml.Linq;
5
6 [WebService(Namespace = "http://tempuri.org/")]
7 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
8 [System.Web.Script.Services.ScriptService]
9 public class WebService : System.Web.Services.WebService {
10 public WebService () {
11 }
12 [WebMethod]
13 public string SayHellow(string Name)
14 {
15 return "Hellow:" + Name;
16 }
17 }
2.js調用webservice方法一
調用方法一
1 function RequestWebserviceByFunctionOne(value)
2 {
3
4 var URL = "http://localhost:2869/JsInvokeWebservice/WebService.asmx";
5 var data;
6 data = '<?xml version="1.0" encoding="utf-8"?>';
7 data = data + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">';
8 data = data + '<soap:Body>';
9 data = data + '<SayHellow xmlns="http://tempuri.org/" >';
10 data = data + '<Name>'+value+'</Name>';
11 data = data + '</SayHellow>';
12 data = data + '</soap:Body>';
13 data = data + '</soap:Envelope>';
14 var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
15 xmlhttp.Open("POST", URL, false);
16 xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml");
17 xmlhttp.Send(data);
18 document.getElementById("data").innerHTML = xmlhttp.responseText;
19 }
3.js調用webservice方法二
調用方法二
1 function RequestWebserviceByFunctionTwo(data){
2
3 var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
4 var URL="http://localhost:2869/JsInvokeWebservice/WebService.asmx/SayHellow?Name=Zach";
5 xmlhttp.Open("GET",URL, false);
6 xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8");
7 xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHellow");
8 xmlhttp.Send(data);
9 if(xmlhttp.status==200) {
10 document.write(xmlhttp.responseText);
11 }
12 xmlhttp = null;
13 }
備忘:1.對於方法一,需要發送的那堆東西可以在webservice的測試頁面中找到,自己拼湊加上對應的參數就行
2.對於方法二,可能會引發“URL 意外地以“/SayHellow”結束,請求格式無法識別”的錯誤,解決此問題,
只要在web.config中的system.web的 節中,加入如下代碼,即可解決( <webServices><protocols>
<add name="HttpPost"/><add name="HttpGet"/></protocols></webServices>)
3.其餘非同步呼叫代碼已在本部落格中有描述,不再累述