本文實例為大家分享了js調用webservice構造SOAP進行身份驗證的相關內容,注釋清除,供大家參考,具體內容如下
<html> <head> <title>無標題頁</title> <script language="javascript" type="text/javascript"> // <!CDATA[ //define var xmlhttp; var value=new Array(); var variable=new Array(); //Show Response MSG. function handleStateChange() { var h=document.getElementById("Label1"); if(xmlhttp.readyState==4) { if(xmlhttp.status==200) { alert(xmlhttp.responseText); h.innerHTML=xmlhttp.responseText; //h.innerHTML=xmlhttp.responseXML; } else if(xmlhttp.status==404) { h.innerHTML="<br>找不到請求的服務器資源!"; } } else if(xmlhttp.readyState==0) { h.innerHTML="<br>未初始化!"; } else if(xmlhttp.readyState==1) { h.innerHTML="<br>正在加載……!"; } else if(xmlhttp.readyState==2) { h.innerHTML="<br>已經加載完成!"; } else if(xmlhttp.readyState==3) { h.innerHTML="<br>正在和服務器交互"; } else { h.innerHTML=xmlhttp.responseXML; } } //Get Request Data's length function getlen(str) { var bytesCount=0; for (var i = 0; i < str.length; i++) { var c = str.charAt(i); if (/^[u0000-u00ff]$/.test(c)) //匹配雙字節 { bytesCount += 1; } else { bytesCount += 2; } } return bytesCount; } //Create XMLHttpRequest Object function createXMLHttpRequest() { if(window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequst) { xmlhttp=new XMLHttpRequest(); } } //send Request By HTTP POST //實際上這段代碼就是用JS構造一個字符串,而這個字符串就是通過浏覽器查看WEBSERVICE時方法時出現的那段 function RequestByPost(method,variable,value,url,_Namespace) { createXMLHttpRequest(); var data; data = '<?xml version="1.0" encoding="utf-8"?>'; data = data + '<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/">'; //加了這段可以實現soap頭 //UserName ,Pwd這是我的SOAP驗證形式,需替換 data = data + "<soap:Header>" data = data + '<UserSoapHeader xmlns="http://tempuri.org/">' data = data + "<UserName>admin</UserName>" data = data + "<Pwd>faaaa</Pwd>" data = data + "</UserSoapHeader>" data = data + "</soap:Header>" data = data + '<soap:Body>'; data = data + '<'+method+' xmlns="'+_Namespace+'">'; for(var i=0;i<variable.length;i++) { data = data + '<'+variable[i]+'>'+value[i]+'</'+variable[i]+'>'; } data = data + '</'+method+'>'; data = data + '</soap:Body>'; data = data + '</soap:Envelope>'; xmlhttp.onreadystatechange=handleStateChange; xmlhttp.Open("POST",url, true); xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8"); //xmlhttp.SetRequestHeader ("Content-Length",getlen(data)); xmlhttp.SetRequestHeader ("SOAPAction",_Namespace+method); xmlhttp.Send(data); alert(data); } //WeatherReport Test: function Button2_onclick() { //方法名,參數名,參數值,服務URL,服務所使用命名空間 RequestByPost("HelloWorld",[],[],"http://localhost:13267/SERVICES/WebService.asmx","http://tempuri.org/"); } window.onload = function(){ Button2_onclick(); } // ]]> </script> </head> <body> <label id='Label1'>ss</label> </body> </html>
以上就是本文的全部內容,希望對大家學習javascript程序設計有所幫助。