最简单的SOAP示例

Tho*_*att 235 javascript soap

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

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

  • 功能性(换句话说实际工作)
  • 发送至少一个可以在代码中的其他位置设置的参数
  • 处理至少一个可以在代码中的其他位置读取的结果值
  • 使用大多数现代浏览器版本
  • 尽量清晰,尽可能短,不使用外部库

小智 198

这是我可以创建的最简单的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(xmlhttp.responseText);
                        // 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 -->
Run Code Online (Sandbox Code Playgroud)

  • 最近不得不使用它来支持遗留代码。遇到了缺少标头的问题,该问题导致“EndpointDispatcher 处的 ContractFilter 不匹配”。在 `xmlhttp.send(sr)` 之前添加 `xmlhttp.setRequestHeader('SOAPAction', 'http://myurl.com/action');` 修复了该问题。 (3认同)
  • 发送<soapenv:Header>怎么样?我尝试将我的标头标签构建到sr变量中,但是服务器收到了一个空的soapenv:Header (2认同)
  • @Rickchip,[此处](/sf/answers/3579303451/)是解决问题的更通用方法:可以在需要时通过调用“setRequestHeader()”来添加标头。 (2认同)

小智 81

浏览器处理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...
Run Code Online (Sandbox Code Playgroud)

另外两个选择:


Pre*_*aul 47

除非Web服务与您的页面位于同一个域中,否则无法使用直接JavaScript执行此操作.编辑:在2008年和IE <10中,除非服务与您的页面位于同一个域,否则无法使用直接javascript完成此操作.

如果Web服务位于另一个域[并且您必须支持IE <10],那么您将必须在您自己的域上使用代理页面来检索结果并将其返回给您.如果您不需要旧的IE支持,则需要为您的服务添加CORS支持.在任何一种情况下,你应该使用类似于timyates建议的lib,因为你不想自己解析结果.

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

简短的回答是:不要从javascript发出SOAP请求.使用Web服务从另一个域请求数据,如果这样做,则在服务器端解析结果并以js友好形式返回它们.

  • re"无法完成":如果客户端支持[跨源资源共享](http://www.w3.org/TR/cors/),今天可以使用(大多数)直接JavaScript完成.希望在3 - 4年内它将普遍可用. (10认同)
  • @Constantin,CORS将允许它,如果你愿意只支持更新的浏览器,如果你有控制服务器,也可以在那里添加CORS支持.话虽这么说,我仍然认为SOAP调用应该只在服务器之间进行,而客户端应该使用像JSON这样更友好的JS. (2认同)
  • -1 因为这不能回答问题。在您的域上拥有无法“修改以返回 JSON”的第 3 方应用程序的用例怎么样? (2认同)

Yaa*_*lis 13

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

此脚本使用$ .ajax发送SOAPEnvelope.它可以将XML DOM,XML字符串或JSON作为输入,并且响应也可以作为XML DOM,XML字符串或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
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 8

有没人试过这个?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
}
});
Run Code Online (Sandbox Code Playgroud)

会导致

<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>
Run Code Online (Sandbox Code Playgroud)


Ric*_*une 7

托马斯:

JSON是前端使用的首选,因为它是javascript.因此,您无需处理XML.因此,SOAP不使用库就很痛苦.有人提到了SOAPClient,它是一个很好的库,我们从它开始为我们的项目.但它有一些限制,我们不得不重写它的大块.它已作为SOAPjs发布并支持将复杂对象传递到服务器,并包含一些示例代理代码以使用来自其他域的服务.

  • *"JSON是前端使用的首选,因为它是javascript."* - JSON是*不是*JavaScript.(它看起来像JavaScript.) (2认同)
  • https://en.wikipedia.org/wiki/JSON - 字面意思是"JavaScript Object Notation",虽然我同意JSON是一种规范而不是一种语言,因此肯定是"不是javascript"你必须同意它命名的方式可能很容易混淆人们. (2认同)

Hka*_*hia 6

<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>
Run Code Online (Sandbox Code Playgroud)

听听最好的 JavaScript 和 SOAP 教程以及示例。

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