最简单的SOAP示例

什么是使用Javascript的最简单的SOAP例子?

为了尽可能有用,答案应该是:

  • function性(换句话说,实际上是工作)
  • 发送至less一个可以在代码中设置的参数
  • 处理至less一个可以在代码中读取的结果值
  • 使用最现代的浏览器版本
  • 尽可能清楚,尽可能短,而不使用外部库

这是我可以创build的最简单的JavaScript SOAP客户端。

<html> <head> <title>SOAP JavaScript Client Test</title> <script type="text/javascript"> function soap() { var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST', 'https://somesoapurl.com/', true); // build SOAP request var sr = '<?xml version="1.0" encoding="utf-8"?>' + '<soapenv:Envelope ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' + 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' + 'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' + '<soapenv:Body>' + '<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' + '<username xsi:type="xsd:string">login_username</username>' + '<password xsi:type="xsd:string">password</password>' + '</api:some_api_call>' + '</soapenv:Body>' + '</soapenv:Envelope>'; xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { alert('done. use firebug/console to see network response'); } } } // Send the POST request xmlhttp.setRequestHeader('Content-Type', 'text/xml'); xmlhttp.send(sr); // send request // ... } </script> </head> <body> <form name="Demo" action="" method="post"> <div> <input type="button" value="Soap" onclick="soap();" /> </div> </form> </body> </html> <!-- typo --> 

浏览器处理XMLHttpRequest的方式有很多,这个JS代码可以在所有的浏览器上运行:
https://github.com/ilinsky/xmlhttprequest

这个JS代码将XML转换成易于使用的JavaScript对象:
http://www.terracoder.com/index.php/xml-objectifier

上面的JS代码可以包含在页面中,以满足您无需外部库的要求。

 var symbol = "MSFT"; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote",true); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4) { alert(xmlhttp.responseText); // http://www.terracoder.com convert XML to JSON var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML); var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text; // Result text is escaped XML string, convert string to XML object then convert to JSON object json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result)); alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text); } } xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote"); xmlhttp.setRequestHeader("Content-Type", "text/xml"); var xml = '<?xml version="1.0" encoding="utf-8"?>' + '<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:Body> ' + '<GetQuote xmlns="http://www.webserviceX.NET/"> ' + '<symbol>' + symbol + '</symbol> ' + '</GetQuote> ' + '</soap:Body> ' + '</soap:Envelope>'; xmlhttp.send(xml); // ...Include Google and Terracoder JS code here... 

另外两个选项:

除非Web服务与页面位于同一个域中,否则这不能直接使用JavaScript。 编辑:在2008年和IE浏览器<10这不能用直的JavaScript来完成,除非服务是在您的网页相同的域。

如果Web服务在另一个域上(并且您必须支持IE <10],那么您将不得不在您自己的域上使用代理页面来检索结果并将其返回给您。 如果您不需要旧的IE支持,那么您需要将CORS支持添加到您的服务。 无论哪种情况,都应该使用类似于timyates所build议的lib,因为你不想自己parsing结果。

如果Web服务位于您自己的域中,则不要使用SOAP。 没有理由这样做。 如果Web服务位于您自己的域上,那么修改它以便它可以返回JSON并为您节省处理SOAP带来的所有麻烦的麻烦。

简短的回答是:不要从JavaScript做出SOAP请求。 使用Web服务从另一个域请求数据,如果你这样做,然后parsing服务器端的结果,并以友好的forms返回。

您可以使用jquery.soap插件为您完成工作。

该脚本使用$ .ajax发送SOAPEnvelope。 它可以将XML DOM,XMLstring或JSON作为input,响应可以作为XML DOM,XMLstring或JSON返回。

来自网站的示例用法:

 $.soap({ url: 'http://my.server.com/soapservices/', method: 'helloWorld', data: { name: 'Remy Blom', msg: 'Hi!' }, success: function (soapResponse) { // do stuff with soapResponse // if you want to have the response as JSON use soapResponse.toJSON(); // or soapResponse.toString() to get XML string // or soapResponse.toXML() to get XML DOM }, error: function (SOAPResponse) { // show error } }); 

托马斯:

JSON是前端使用的首选,因为它是JavaScript。 所以你没有XML来处理。 因为这个原因,SOAP是一个不使用库的痛苦。 有人提到SOAPClient,这是一个很好的库,我们开始为它的项目。 然而,它有一些限制,我们不得不重写它的大块。 它已经作为SOAPjs发布,并支持将复杂的对象传递给服务器,并包含一些示例代理代码,以消耗来自其他域的服务。

有没有人试过这个? https://github.com/doedje/jquery.soap

看起来很容易实现。

例:

 $.soap({ url: 'http://my.server.com/soapservices/', method: 'helloWorld', data: { name: 'Remy Blom', msg: 'Hi!' }, success: function (soapResponse) { // do stuff with soapResponse // if you want to have the response as JSON use soapResponse.toJSON(); // or soapResponse.toString() to get XML string // or soapResponse.toXML() to get XML DOM }, error: function (SOAPResponse) { // show error } }); 

会导致

 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <helloWorld> <name>Remy Blom</name> <msg>Hi!</msg> </helloWorld> </soap:Body> </soap:Envelope> 
 <html> <head> <title>Calling Web Service from jQuery</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnCallWebService").click(function (event) { var wsUrl = "http://abc.com/services/soap/server1.php"; var soapRequest ='<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:Body> <getQuote xmlns:impl="http://abc.com/services/soap/server1.php"> <symbol>' + $("#txtName").val() + '</symbol> </getQuote> </soap:Body></soap:Envelope>'; alert(soapRequest) $.ajax({ type: "POST", url: wsUrl, contentType: "text/xml", dataType: "xml", data: soapRequest, success: processSuccess, error: processError }); }); }); function processSuccess(data, status, req) { alert('success'); if (status == "success") $("#response").text($(req.responseXML).find("Result").text()); alert(req.responseXML); } function processError(data, status, req) { alert('err'+data.state); //alert(req.responseText + " " + status); } </script> </head> <body> <h3> Calling Web Services with jQuery/AJAX </h3> Enter your name: <input id="txtName" type="text" /> <input id="btnCallWebService" value="Call web service" type="button" /> <div id="response" ></div> </body> </html> 

听说是最好的JavaScript与SOAP教程的例子。

http://www.codeproject.com/Articles/12816/JavaScript-SOAP-Client

最简单的例子将包括:

  1. 获取用户input。
  2. 编写与此类似的XML SOAP消息

     <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:Body> <GetInfoByZIP xmlns="http://www.webserviceX.NET"> <USZip>string</USZip> </GetInfoByZIP> </soap:Body> </soap:Envelope> 
  3. 使用XHR将消息发布到webservice url

  4. parsingweb服务的XML SOAP响应与此类似

     <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetInfoByZIPResponse xmlns="http://www.webserviceX.NET"> <GetInfoByZIPResult> <NewDataSet xmlns=""> <Table> <CITY>...</CITY> <STATE>...</STATE> <ZIP>...</ZIP> <AREA_CODE>...</AREA_CODE> <TIME_ZONE>...</TIME_ZONE> </Table> </NewDataSet> </GetInfoByZIPResult> </GetInfoByZIPResponse> </soap:Body> </soap:Envelope> 
  5. 向用户呈现结果。

但是如果没有外部的JavaScript库,这很麻烦。

一些很好的例子(和一个现成的JavaScript SOAP客户端!)在这里: http : //plugins.jquery.com/soap/

检查自述文件,并注意同一浏览器的限制。

使用JavaScript轻松使用SOAP Web服务 – > 清单B.

 function fncAddTwoIntegers(a, b) { varoXmlHttp = new XMLHttpRequest(); oXmlHttp.open("POST", "http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'", false); oXmlHttp.setRequestHeader("Content-Type", "text/xml"); oXmlHttp.setRequestHeader("SOAPAction", "http://tempuri.org/AddTwoIntegers"); oXmlHttp.send(" \ <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:Body> \ <AddTwoIntegers xmlns='http://tempuri.org/'> \ <IntegerOne>" + a + "</IntegerOne> \ <IntegerTwo>" + b + "</IntegerTwo> \ </AddTwoIntegers> \ </soap:Body> \ </soap:Envelope> \ "); return oXmlHttp.responseXML.selectSingleNode("//AddTwoIntegersResult").text; } 

这可能不符合您的所有要求,但实际上回答您的问题是一个开始。 (我为ActiveXObject(“MSXML2.XMLHTTP”) )切换XMLHttpRequest( )。

 function SoapQuery(){ var namespace = "http://tempuri.org/"; var site = "http://server.com/Service.asmx"; var xmlhttp = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0"); xmlhttp.setOption(2, 13056 ); /* if use standard proxy */ var args,fname = arguments.callee.caller.toString().match(/ ([^\(]+)/)[1]; /*Имя вызвавшей ф-ции*/ try { args = arguments.callee.caller.arguments.callee.toString().match(/\(([^\)]+)/)[1].split(","); } catch (e) { args = Array();}; xmlhttp.open('POST',site,true); var i, ret = "", q = '<?xml version="1.0" encoding="utf-8"?>'+ '<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:Body><'+fname+ ' xmlns="'+namespace+'">'; for (i=0;i<args.length;i++) q += "<" + args[i] + ">" + arguments.callee.caller.arguments[i] + "</" + args[i] + ">"; q += '</'+fname+'></soap:Body></soap:Envelope>'; // Send the POST request xmlhttp.setRequestHeader("MessageType","CALL"); xmlhttp.setRequestHeader("SOAPAction",namespace + fname); xmlhttp.setRequestHeader('Content-Type', 'text/xml'); //WScript.Echo("Запрос XML:" + q); xmlhttp.send(q); if (xmlhttp.waitForResponse(5000)) ret = xmlhttp.responseText; return ret; }; function GetForm(prefix,post_vars){return SoapQuery();}; function SendOrder2(guid,order,fio,phone,mail){return SoapQuery();}; function SendOrder(guid,post_vars){return SoapQuery();}; 

Angularjs $ http wrap基于XMLHttpRequest 。 只要在标题内容中设置下面的代码就可以了。

 "Content-Type": "text/xml; charset=utf-8" 

例如:

 function callSoap(){ var url = "http://www.webservicex.com/stockquote.asmx"; var soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://www.webserviceX.NET/\"> "+ "<soapenv:Header/> "+ "<soapenv:Body> "+ "<web:GetQuote> "+ "<web:symbol></web:symbol> "+ "</web:GetQuote> "+ "</soapenv:Body> "+ "</soapenv:Envelope> "; return $http({ url: url, method: "POST", data: soapXml, headers: { "Content-Type": "text/xml; charset=utf-8" } }) .then(callSoapComplete) .catch(function(message){ return message; }); function callSoapComplete(data, status, headers, config) { // Convert to JSON Ojbect from xml // var x2js = new X2JS(); // var str2json = x2js.xml_str2json(data.data); // return str2json; return data.data; } }