JavaScript 如何调用 Web Service

1. 通过 webbehavior.htc调用 Web Service

webservice.htc 是微软提供的一个对 Web  Servie 常用方法的封装,可以从微软官方网站下载,安装IE webcontrols时也会安装到你的网站根目录下,使用时需要注意路径。请注意代码中body的属性设置。 
实现步骤如下。 
(1)首先,我们先创建一个加法运算的 Web Service,例如: 

using  System.Web; 
using  System.Web.Services; 
namespace  WebService1 
{ 
        //<summary> 
        //Service1 的摘要说明 
        //</summary> 
        [WebService(Namespace  = "http://tempuri.org/")] 
        [WebServiceBinding(ConformsTo  =  WsiProfiles.BasicProfile1_1)] 
        [ToolboxItem(false)] 
        public  class  Service1  :  System.Web.Services.WebService 
        {     
               //加法的例子 
               [WebMethod] 
               public  int  Add(int  a,  int  b) 
               { 
                       return  a  +  b; 
               } 
        } 
} 

然后发布,并得到其wsdl。 
(2)下载webbehavior.htc这个文件(本书附件中有),然后放到你的 Web 当前目录下。  
(3)在要调用Web Service的页面中,进行如下修改:

<body> 
<div  id="addservice"  style="behavior:url(webservice.htc)"></div> 
</body> 

这里我们将 div  id命名为有意义的名称,并且指定 style为  webservice行为。接着,我们要书写JavaScript来调用Web Serice了。 
首先,我们在 JavaScript 中调用其 addservice.useService("http://localhost/services/math.asmx?WSDL","MyMath") ;使用id.useService(WSDLL路径,简单的命名方式) ;我们之前设定的 id是 addservice,为了给客户端调用方便,我们这里起了名称,叫 MyMath。而为了保证能正确调用webservice, 必须在body里的 onload事件里,马上加载处理webservice调用的JavaScript,如下: 

<script  language="JavaScript"> 
function  init() 
{ 
    addservice.useService("http://localhost/services/math.asmx?WSDL","MyMath");  
} 
</script> 
<body  onload="init()"> 
<div  id="service"  style="behavior:url(webservice.htc)"> 
</div> 
</body> 

上面我们通过webservice行为,首先得到了返回 webservice的 wsdl,接下来我们就要进行调用了,调用的格式如下: 
iCallID  =  id.FriendlyName.callService([CallbackHandler,]"MethodName", Param1,Param2,  ...); 这里id是我们在div里设置的id,而FridndbyName是我们刚才为方法起的名,这里就是MyMath了,而CallbackHandler 是使用回调函数的过程名,如果无设置的话,则默认是使用onresult所调用的方法来进行处理,而 param1、param2等则是传入的参数了。例如: 

<html xmlns="http://www.w3.org/1999/xhtml">
 <head> 
  <title>Js 调用  WebService实例</title> 
  <script language="JavaScript">       
        function  init() 
        { 
               //改成你自己的实际地址 
            divservice.useService("http://localhost:12074/Service1.asmx?WSDL","MyMath");  
        } 
        function  onWSresult() 
        {               
               if((event.result.error)&&(iCallID==event.result.id))//如果有错误 
               { 
                       //得到详细错误信息 
                       var  xfaultcode =  event.result.errorDetail.code; 
                       var  xfaultstring =  event.result.errorDetail.string; 
                       var  xfaultsoap =  event.result.errorDetail.raw;          
                       //错误处理代码                       
               }    
               else{ 
                       if((!event.result.error)  &&  (iCallID  ==  event.result.id)) 
                       {              
                             divservice.innerHTML= event.result.value;//显示计算结果 
                       } 
                       else 
                       { 
                             alert("Something  else  fired  the  event!"); 
                       }
		}					   
        }          
        </script> 
 </head> 
 <body onload="init()"> 
  <div>
    第1个值:
   <input type="text" id="ip1" name="ip1" />
   <br /> 第2个值:
   <input type="text" id="ip2" name="ip2" />
   <br /> 
   <button onclick="iCallID=divservice.MyMath.callService(&quot;Add&quot;,ip1.value, 
   ip2.value);" id="Button1" type="button">s调用加法方法</button>
   <br /> 结果:
   <div id="divservice" style="behavior:url(webservice.htc)" onresult="onWSresult()"> 
   </div> 
  </div>   
 </body>
</html>

代码中使用了 onresult 方式返回处理结果,并在 div 部分的 onresult 中指定执行处理的方法,这里用的是 onWsresult()方法,其中根据返回的信息来判断是否出错,出错的话则显示。

2. 通过 Microsoft.XMLDOM调用 Web Service 

(1)在页面中添加如下代码: 

<body> 
        <input  type="button"  value="调用"  onclick="getdata()"><br> 
        <span  id="div1"  class="list"></span> 
</body> 

(2)调用WebService返回字符串: 

<head> 
        <title>通过Microsoft.XMLDOM调用WebService</title>       
        <script  language="javascript"> 
            function  getdata() 
            {               
               docSubmit  =new  ActiveXObject("Microsoft.XMLDOM"); 
               docSubmit.async  =  false;      
               docSubmit.load("http://localhost:12074/Service1.asmx/GetProductPrice?ProductId=001");  
               var  s=docSubmit.documentElement.text;  //获取返回结果                       
               div1.innerHTML=s;            
            }    
            //setInterval(getdata,2000);//定时间隔2秒执行          
        </script> 
</head> 

在docSubmit.load()方法中,填写自己实际的 Web Service地址。 
(3)再看一个返回数据集的Web Service方法,例如:

[WebMethod(Description  = "获得产品数据列表")] 
public  string  GetProducts(int  topNum) 
{ 
        Products  pro  =  new  Products();                      
        DataSet  ds  =  pro.GetProducts(topNum); 
        return  ds.GetXml(); 
} 

通过 Get 方式 http://localhost:12074/Service1.asmx/GetProducts?topNum=5 调用实际返回的XML数据: 

<?xml  version="1.0"  encoding="utf-8"  ?>  
<string  xmlns="http://tempuri.org/"> 
<NewDataSet>  
<ds><ProductId>001</ProductId>  <Name>test</Name>  </ds>  
<ds><ProductId>dd</ProductId>  <Name>图书</Name>  </ds>  
<ds><ProductId>dn</ProductId>  <Name>电脑5</Name>  </ds>  
<ds><ProductId>ds</ProductId>  <Name>图书</Name>  </ds>  
<ds><ProductId>jj</ProductId>  <Name>家具</Name>  </ds>  
</NewDataSet> 
</string> 

(4)获取DataSet数据集的调用脚本: 

<head> 
        <title>通过Microsoft.XMLDOM调用WebService</title> 
        <script  language="javascript"> 
           function  getdata() 
           { 
               var  index=0;     
               docSubmit  =new  ActiveXObject("Microsoft.XMLDOM"); 
               docSubmit.async  =  false;      
               docSubmit.load("http://localhost:12074/Service1.asmx/ 
        GetProducts?topNum=5");  
              docSubmit.loadXML(docSubmit.xml.replace(/&lt;/g,"<").replace(/&gt;/g,">")); 
                     
               var  s="";   
               nodeList=docSubmit.documentElement.getElementsByTagName("ds"); 
               for  (i=0;i<nodeList.length;i++) 
               { 
                     s=s+nodeList(i).selectSingleNode("Name").text+'<br>';//显示产品名称 
               }       
               div1.innerHTML=s;       
           }       
        </script> 
</head>

Web Service开发详解
注意 Fromework  1.0 和 Fromework  1.1 是有区别的,在 Fromework  1.1 中的 machine.config(C:\WINNT\Microsoft.NET\Framework\v1.1.4322\CONFIG),默认 Web  Service 去除了 Post、Get 方法。你可在你的  machine.config 中或者只在
webServices项目的Web.config  的<system.web>里加上: 

<webServices> 
        <protocols> 
               <add  name="HttpPost"  /> 
               <add  name="HttpGet"  /> 
        </protocols> 
</webServices>

否则,在IE 地址栏中输入webservices地址访问时,将会出现提示请求格式无法识别。
还有ActiveX 对象不同: 
//Fromework  1.0版本中 
docSubmit  =  new  ActiveXObject("MSXML2.DOMDocument");   
//Fromework  1.1版本中 
docSubmit  =  new  ActiveXObject("Microsoft.XMLDOM");      

3. XMLHTTP POST调用 Web Service 

基本上和RSS阅读器原理相同,通过XML HTTP实现客户端方式的静态读取。

<html  xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
        <title>XMLHTTP-POST</title> 
        <script  language="JavaScript">       
        function  GetHelloWorld_HTTPPOST(i) 
        { 
               var  URL  = "http://localhost:12074/Service1.asmx/GetProductPrice"; 
               var  Params  =  "ProductId="  +  i;//设置post参数 
               var  xmlhttp  =  new  ActiveXObject("Microsoft.XMLHTTP"); 
               xmlhttp.Open("POST",URL,  false); 
               xmlhttp.SetRequestHeader  ("Content-Type", "application/x-www-form-urlencoded"); 
               xmlhttp.SetRequestHeader  ("Content-Length",Params.length); 
               xmlhttp.send(Params); 
               var  x  =      xmlhttp.responseXML;               
               div1.innerHTML=x.childNodes[1].text; 
               //返回调用状态,状态为200说明调用成功,状态为500则说明出错 
               alert(xmlhttp.Status); 
               alert(xmlhttp.StatusText); 
        } 
        </script> 
</head> 
<body> 
<input  type="button"  value="HTTPPOST"  onclick="GetHelloWorld_HTTPPOST('001')"  id="Button2"  name="Button2"> 
<br><div  id="div1"></div> 
</body> 
</html> 

SOAP调用 Web Service

<html  xmlns="http://www.w3.org/1999/xhtml"  > 
<head> 
        <title>SOAP对调用WebService</title> 
        <SCRIPT  language="JavaScript">       
        function  GetHelloWorld_SOAP(i) 
        { 
               var  xmlhttp  =  new  ActiveXObject("Microsoft.XMLHTTP"); 
               var  soapMessage,  soapData,  URL; 
               //设置SOAP信息 
               soapMessage  =  "<?xml  version=\"1.0\"  encoding=\"utf-8\"?>"; 
               soapMessage  +=  "<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/\">"; 
               soapMessage  +=  "<soap:Body>"; 
               //设置SOAP数据  ----  begin  ------ 
               soapData  =  "<GetProductPrice  xmlns=\"http://tempuri.org/\">"; 
               soapData  +=  "        <ProductId>"  +  i  +  "</ProductId>"; 
               soapData  +=  "</GetProductPrice>"; 
               //设置SOAP数据  ----    end    ------ 
              
               soapMessage  =  soapMessage  +  soapData  +  "</soap:Body>"; 
               soapMessage  =  soapMessage  +  "</soap:Envelope>"; 
               URL  = "http://localhost:12074/Service1.asmx";  //WebService地址URL 
               xmlhttp.Open("POST",URL,  false); 
               xmlhttp.SetRequestHeader  ("Content-Type","text/xml;  charset=utf-8"); 
               xmlhttp.SetRequestHeader  ("SOAPAction","http://tempuri.org/ 
     GetProductPrice");//方法名 
               xmlhttp.send(soapMessage); 


               alert(soapMessage)//SOAP数据信息 
               var  x  =      xmlhttp.responseXML; 
               alert('调用结果:'+x.childNodes[1].text); 
               //返回调用状态,状态为200说明调用成功,状态为500则说明出错 
               alert('状态值:'+xmlhttp.Status); 
               alert('状态描述:'+xmlhttp.StatusText); 
        } 
</SCRIPT> 
</head> 
<body> 
<INPUT  type="button"  value="SOAP"  onclick="GetHelloWorld_SOAP('001')" 
      id="Button1"  name="Button1"> 
<INPUT  type="button"  value="异常测试"  onclick="GetHelloWorld_SOAP('')" 
      id="Button3"  name="Button3"><BR><BR> 
<div  id="div1"></div> 
</body> 
</html> 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值