SOAP调用Web Service

SOAP调用Web Service

(示例位置:光盘codech07 WebAppClient JsService4.htm)

  1. <html xmlns="http://www.w3.org/1999/xhtml" >  
  2. <head>  
  3.     <title>SOAP对调用WebService</title>  
  4.     <SCRIPT language="JavaScript">      
  5.     function GetHelloWorld_SOAP(i)  
  6.     {  
  7.         var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
  8.         var soapMessage, soapData, URL;  
  9.         //设置SOAP信息  
  10.         soapMessage = "<?xml version="1.0" encoding="utf-8"?>";  
  11.         soapMessage += "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/  
  12.             XMLSchema-instance"" 
  13.         + " xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap=  
  14.             "http://schemas.xmlsoap.org/soap/envelope/">";  
  15.         soapMessage += "<soap:Body>";  
  16.         //设置SOAP数据 ---- begin ------  
  17.         soapData = "<GetProductPrice xmlns="http://tempuri.org/">";  
  18.         soapData += "    <ProductId>" + i + "</ProductId>";  
  19.         soapData += "</GetProductPrice>";  
  20.         //设置SOAP数据 ----  end  ------  
  21.           
  22.         soapMessage = soapMessage + soapData + "</soap:Body>";  
  23.         soapMessage = soapMessage + "</soap:Envelope>";  
  24.         URL = "http://localhost:12074/Service1.asmx"; //WebService地址URL  
  25.         xmlhttp.Open("POST",URL, false);  
  26.         xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8");  
  27.         xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/  
  28.             GetProductPrice");//方法名  
  29.         xmlhttp.send(soapMessage);  
  30.         alert(soapMessage)//SOAP数据信息  
  31.         var x =   xmlhttp.responseXML;  
  32.         alert('调用结果:'+x.childNodes[1].text);  
  33.         //返回调用状态,状态为200说明调用成功,状态为500则说明出错  
  34.         alert('状态值:'+xmlhttp.Status);  
  35.         alert('状态描述:'+xmlhttp.StatusText);  
  36.     }  
  37. </SCRIPT>  
  38. </head>  
  39. <body>  
  40. <INPUT type="button" value="SOAP" onclick="GetHelloWorld_SOAP('001')" 
  41.         id="Button1" name="Button1">  
  42. <INPUT type="button" value="异常测试" onclick="GetHelloWorld_SOAP('')" 
  43.         id="Button3" name="Button3"><BR><BR>  
  44. <div id="div1"></div>  
  45. </body>  
  46. </html> 

具体XMLHTTP的用法和属性可以参考第6.3.8节中的内容。