Javascript调用Webservice(整理)

    看了博客园和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.其余异步调用代码已在本博客中有描述,不再累述

      

posted @ 2011-05-26 23:56  --中庸--  阅读(1155)  评论(0编辑  收藏  举报