如何从Javascript/jQuery调用SOAP Web服务

18
我希望能够直接从JavaScript调用SOAP WebService,但一直没有成功。我认为我必须构建SOAP包装器(见下文),同时我使用了jQuery。
首先,我需要确定是否可以调用位于其他地方的SOAP Webservice,即是否有跨域限制等限制。
另外,我不确定需要使用什么URL,SOAP服务使用Ladon公开,为了调试目的,我已经使用soapUI检查了WS正常工作,并找到以下URL:
- WSDL URL: http://192.168.1.5/ws/MyWS/soap/description//据我所知,不能是这个 - 服务端点:http://192.168.1.5/ws/MyWS/soap - SOAPAction:http://192.168.1.5/ws/MyWS/soap/myOperation 我认为应该使用端点或SOAPAction,但它没有起作用。我可能在这里漏掉了什么,或者后面的Javascript代码有很多错误,我不能确定。
现在这是我的实际JS调用(注释中有一些问题):
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<head>

<script type="text/javascript" src="ressources/jquery-1.7.1.min.js"></script>

<script type="text/javascript">

// inspired by http://openlandscape.net/2009/09/25/call-soap-xm-web-services-with-jquery-ajax/

var soapServiceURL = 'http://192.168.1.5/ws/MyWS/soap/myOperation; // not sure what to put here from a LADON point of view

function callSOAPWS(myParameter)
{
  var soapMessage =
  '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:LDetector"> \
     <soapenv:Header/> \
     <soapenv:Body> \
        <urn:myOperation soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> \
           <myParameter xsi:type="xsd:string">' + myParameter + '</myParameter > \
        </urn:myOperation > \
     </soapenv:Body> \
  </soapenv:Envelope>';

  alert("Check SOAP: [" + soapMessage + "]");

  jQuery.ajax({
          url: soapServiceURL,
          type: "POST",
          dataType: "xml",
          data: soapMessage,
          contentType: "text/xml; charset=\"utf-8\"",

          //processData: false,   // what is it for? may be should be true when using 'complete:' ?
          //timeout: 5000,

          // below I first try to have only 'complete:' then I tried to have 'success:' + 'error:', then the 3. Nothing seems to be ok. I do not find which one i should use.
          complete: myCallback,

          success: function( response ){
              document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML + '\n' + 'success!' + '\n';
              alert("success!!!");
          },

          error: function(XMLHttpRequest,textStatus, errorThrown){
              document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML + '\n' + 'error : ' + textStatus + '\n';
              alert("error : " + textStatus);
          }

  });

  alert('if we reach this line, is it a fail?!');
  return false;
}

function myCallback(xmlHttpRequest, status)
{
  jQuery(xmlHttpRequest.responseXML)
      .find('detected')
      .each(function()
   {
     var result = jQuery(this).find('result').text();
     document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML + '\n' + result + '\n';
     alert('ok : [' + result + ']');
   });
}

// https://dev59.com/B2fWa4cB1Zd3GeqPeSyH

jQuery(document).ready(function() {
    callSOAPWS('this is a test');
});

</script>
</head>
<body>

<div id="debug" style="background-color:#EEEEEE; height:250px; width:600px; overflow:auto;">&nbsp;</div>

</body>
</html>

最好的问候

编辑: 在继续尝试寻找答案时,我已经阅读了 => 最简单的SOAP示例 ,Prestaul说“除非Web服务与您的页面在同一个域上,否则无法使用纯JavaScript完成此操作。”所以,也许我正在尝试做一些不可能的事情?这是为什么它不能工作的原因吗?

3个回答

25
您不能发送跨域AJAX请求,因为浏览器内置了同源策略限制。为了使其工作,包含jQuery代码的HTML页面必须托管在与Web服务(http://192.168.1.5/ws/MyWS/)相同的域上。
有一些解决方法涉及在服务器上使用JSONP,但是由于您的Web服务是SOAP,这种方法行不通。
如果您无法将JavaScript移动到与Web服务相同的域中,则唯一可靠的方法是构建一个服务器端脚本,该脚本将托管在与JavaScript代码相同的域上,并充当两个域之间的桥梁。因此,您将向服务器端脚本发送AJAX请求,该脚本将调用远程Web服务并返回结果。

谢谢,所以我错了,认为使用SOAP与完整的JS客户端是一个变通方法。是的,我已经测试了我上面放置的代码,在从同一服务器使用时可以工作。顺便说一下,我还需要其他服务器也能够这样做...我会看看你建议的方式。 - user1340802

13

这个怎么样? 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>

1
以下代码运行良好。也许它可以帮助你。
    var SoaMessage = '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" >'
                + '<soapenv:Header/>'
                  + '<soapenv:Body>'
                    + '<myoperation soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns="http://MyService/"> '
                     + ' <AgencyId xsi:type="xsd:string">ADBC</AgencyId >'
                  + '</myoperation >'
                 + '</soapenv:Body>'
             + '</soapenv:Envelope>';
    var url = "http://XXXXXXX/XXX/XXXXX?wsdl";
    $.support.cors = true;
    $.ajax({
        type: "POST",
        url: url,
        jsonpCallback: "MyCallbackDED",
        dataType: "xml",
        processData: false,
        contentType: "text/xml; charset=\"utf-8\"",
        success: function (msg) {
            alert("suc: " + msg.tradeLicenseData.master[0].arabicAddress + ": " + msg.tradeLicenseData.master[0].arabicAddress);

        },
        error: function (msg) {
            alert("Failed: " + msg.status + ": " + msg.statusText);
        }

    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接