El ejemplo de SOAP más simple

Resuelto Thomas Bratt asked hace 15 años • 13 respuestas

¿Cuál es el ejemplo SOAP más simple usando Javascript?

Para que sea lo más útil posible, la respuesta debería:

  • Ser funcional (en otras palabras, realmente funcionar)
  • Envíe al menos un parámetro que se pueda configurar en otra parte del código
  • Procese al menos un valor de resultado que se pueda leer en otra parte del código.
  • Trabaja con la mayoría de las versiones modernas del navegador.
  • Sea lo más claro y breve posible, sin utilizar una biblioteca externa
Thomas Bratt avatar Sep 24 '08 05:09 Thomas Bratt
Aceptado

Este es el cliente SOAP JavaScript más simple que puedo crear.

<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 -->
stackoverflow128 avatar Jul 09 '2012 22:07 stackoverflow128

Hay muchas peculiaridades en la forma en que los navegadores manejan XMLHttpRequest; este código JS funcionará en todos los navegadores:
https://github.com/ilinsky/xmlhttprequest

Este código JS convierte XML en objetos JavaScript fáciles de usar:
http://www.terracoder.com/index.php/xml-objectifier

El código JS anterior se puede incluir en la página para cumplir con el requisito de no tener una biblioteca externa.

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...

Otras dos opciones:

  • Cliente SOAP JavaScript:
    http://www.guru4.net/articoli/javascript-soap-client/en/

  • Genere JavaScript desde un WSDL:
    https://cwiki.apache.org/confluence/display/CXF20DOC/WSDL+to+Javascript

Chris Stuart avatar Nov 08 '2009 04:11 Chris Stuart

Esto no se puede hacer con JavaScript directo a menos que el servicio web esté en el mismo dominio que su página. Editar: en 2008 y en IE <10, esto no se puede hacer con JavaScript directo a menos que el servicio esté en el mismo dominio que su página.

Si el servicio web está en otro dominio [y debe admitir IE <10], tendrá que utilizar una página proxy en su propio dominio que recuperará los resultados y se los devolverá. Si no necesita soporte para IE antiguo, debe agregar soporte CORS a su servicio. En cualquier caso, debe usar algo como la biblioteca que timyates sugirió porque no quiere tener que analizar los resultados usted mismo.

Si el servicio web está en su propio dominio, no utilice SOAP. No hay ninguna buena razón para hacerlo. Si el servicio web está en su propio dominio, modifíquelo para que pueda devolver JSON y ahórrese la molestia de lidiar con todas las molestias que conlleva SOAP.

La respuesta corta es: no realice solicitudes SOAP desde javascript. Utilice un servicio web para solicitar datos de otro dominio y, si lo hace, analice los resultados en el lado del servidor y devuélvalos en un formato compatible con js.

Prestaul avatar Sep 24 '2008 02:09 Prestaul

¿Alguien ha probado esto? https://github.com/doedje/jquery.soap

Parece muy fácil de implementar.

Ejemplo:

$.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
}
});

resultará en

<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>
geekasso avatar Sep 23 '2015 19:09 geekasso