Javascript 最简单的SOAP示例

Javascript 最简单的SOAP示例,javascript,soap,Javascript,Soap,使用Javascript的最简单SOAP示例是什么 为了尽可能有用,答案应该是: 发挥作用(换句话说,实际工作) 至少发送一个可在代码中其他位置设置的参数 处理至少一个可在代码中其他位置读取的结果值 使用最新的浏览器版本 在不使用外部库的情况下,尽可能清晰和简短 最简单的示例包括: 获取用户输入 编写与此类似的XML SOAP消息 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

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

  • 发挥作用(换句话说,实际工作)
  • 至少发送一个可在代码中其他位置设置的参数
  • 处理至少一个可在代码中其他位置读取的结果值
  • 使用最新的浏览器版本
  • 在不使用外部库的情况下,尽可能清晰和简短

    • 最简单的示例包括:

    • 获取用户输入
    • 编写与此类似的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>
      
      <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>
      
      
      一串
      
    • 使用XHR将消息发布到webservice url

    • 解析webservice的XMLSOAP响应类似于

      <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>
      
      <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>
      
      
      ...
      ...
      ...
      ...
      ...
      
    • 向用户展示结果

    • 但是,如果没有外部JavaScript库,这将是一件非常麻烦的事情。

      除非web服务与您的页面位于同一个域中,否则直接使用JavaScript是无法做到这一点的。编辑:2008年和IEThomas:


      前端使用JSON是首选,因为我们可以轻松查找。因此,您没有XML可处理。因此,如果不使用库,SOAP是一种痛苦。有人提到SOAPClient,它是一个很好的库,我们从它开始我们的项目。然而,它有一些局限性,我们不得不重写它的大部分。它已发布为,支持将复杂对象传递到服务器,并包含一些示例代理代码,用于使用其他域的服务。

      浏览器处理XMLHttpRequest的方式有许多怪癖,此JS代码将在所有浏览器中运行:

      此JS代码将XML转换为易于使用的JavaScript对象:

      上面的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...
      
      var symbol=“MSFT”;
      var xmlhttp=new XMLHttpRequest();
      open(“POST”http://www.webservicex.net/stockquote.asmx?op=GetQuote“,对);
      xmlhttp.onreadystatechange=函数(){
      if(xmlhttp.readyState==4){
      警报(xmlhttp.responseText);
      // http://www.terracoder.com 将XML转换为JSON
      var json=XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
      var result=json.Body[0]。GetQuoteResponse[0]。GetQuoteResult[0]。文本;
      //结果文本是转义的XML字符串,将字符串转换为XML对象,然后转换为JSON对象
      json=XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(结果));
      警报(symbol+'Stock Quote:$'+json.Stock[0]。最后一个[0]。文本);
      }
      }
      setRequestHeader(“SOAPAction”http://www.webserviceX.NET/GetQuote");
      setRequestHeader(“内容类型”,“text/xml”);
      var xml=''+
      '' + 
      ' ' +
      ' ' +
      ''+符号+''+
      ' ' +
      ' ' +
      '';
      send(xml);
      //…这里包括谷歌和Terracoder JS代码。。。
      
      其他两种选择:

      • JavaScript SOAP客户端:

      • 从WSDL生成JavaScript:

      ->

      函数FNCADDTWO整数(a,b)
      {
      varoXmlHttp=newXMLHttpRequest();
      打开(“POST”,
      "http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'",
      假);
      setRequestHeader(“内容类型”、“文本/xml”);
      setRequestHeader(“SOAPAction”http://tempuri.org/AddTwoIntegers");
      oXmlHttp.send(“\
      \
      \
      \
      “+a+”\
      “+b+”\
      \
      \
      \
      ");
      返回oXmlHttp.responseXML.selectSingleNode(“//AddTwoIntegersResult”).text;
      }
      

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

      这是我能创建的最简单的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 -->
      
      
      soapjavascript客户端测试
      函数soap(){
      var xmlhttp=new XMLHttpRequest();
      xmlhttp.open('POST','https://somesoapurl.com/",对),;
      //生成SOAP请求
      var sr=
      '' +
      '' +
      '' +
      '' +
      '登录\用户名'+
      “密码”+
      '' +
      '' +
      '';
      xmlhttp.onreadystatechange=函数(){
      if(xmlhttp.readyState==4){
      if(xmlhttp.status==200){
      警报(xmlhttp.responseText);
      //警报(“完成。使用firebug/控制台查看网络响应”);
      }
      }
      }
      //发送POST请求
      setRequestHeader('Content-Type','text/xml');
      xmlhttp.send(sr);
      //发送请求
      // ...
      }
      
      
      从jQuery调用Web服务
      $(文档).ready(函数(){
      $(“#btnCallWebService”)。单击(函数(事件){
      var wsUrl=”http://abc.com/services/soap/server1.php";
      var soapRequest=''+$(“#txtName”).val()+'';
      警报(soapRequest)
      $.ajax({
      类型:“POST”,
      url:wsUrl,
      contentType:“text/xml”,
      数据类型:“xml”,
      数据:soapRequest,
      成功:成功,,
      错误:processError
      });
      });
      });
      函数processSuccess(数据、状态、请求){alert('success');
      如果(状态=“成功”)
      $(“#response”).text($(req.responseXML.find(“Result”).text());
      警报(请求响应XML);
      }
      功能处理错误(数据、状态、请求){
      警报(“错误”+数据状态);
      //警报(请求响应文本+“”+状态);
      }
      
      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();};
      
      $.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({
      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>
      
      "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;
      
          }
      
      }
      
      const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
      const DOMParser = require('xmldom').DOMParser;
      
      function parseXml(text) {
          let parser = new DOMParser();
          let xmlDoc = parser.parseFromString(text, "text/xml");
          Array.from(xmlDoc.getElementsByTagName("reference")).forEach(function (item) {
              console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);
          });
      
      }
      
      function soapRequest(url, payload) {
          let xmlhttp = new XMLHttpRequest();
          xmlhttp.open('POST', url, true);
      
          // build SOAP request
          xmlhttp.onreadystatechange = function () {
              if (xmlhttp.readyState == 4) {
                  if (xmlhttp.status == 200) {
                      parseXml(xmlhttp.responseText);
                  }
              }
          }
      
          // Send the POST request
          xmlhttp.setRequestHeader('Content-Type', 'text/xml');
          xmlhttp.send(payload);
      }
      
      soapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap', 
          `<?xml version="1.0" encoding="UTF-8"?>
          <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
          <S:Header />
          <S:Body>
              <ns4:getReferences xmlns:ns4="http://webservice.cdb.ebi.ac.uk/"
                  xmlns:ns2="http://www.scholix.org"
                  xmlns:ns3="https://www.europepmc.org/data">
                  <id>C7886</id>
                  <source>CTX</source>
                  <offSet>0</offSet>
                  <pageSize>25</pageSize>
                  <email>ukpmc-phase3-wp2b---do-not-reply@europepmc.org</email>
              </ns4:getReferences>
          </S:Body>
          </S:Envelope>`);
      
      npm install xmlhttprequest
      npm install xmldom
      
      node soap-node.js
      
      Title:  Perspective: Sustaining the big-data ecosystem.
      Title:  Making proteomics data accessible and reusable: current state of proteomics databases and repositories.
      Title:  ProteomeXchange provides globally coordinated proteomics data submission and dissemination.
      Title:  Toward effective software solutions for big biology.
      Title:  The NIH Big Data to Knowledge (BD2K) initiative.
      Title:  Database resources of the National Center for Biotechnology Information.
      Title:  Europe PMC: a full-text literature database for the life sciences and platform for innovation.
      Title:  Bio-ontologies-fast and furious.
      Title:  BioPortal: ontologies and integrated data resources at the click of a mouse.
      Title:  PubMed related articles: a probabilistic topic-based model for content similarity.
      Title:  High-Impact Articles-Citations, Downloads, and Altmetric Score.