2012-10-09 94 views
13

Me gustaría llamar a un SOAP WebService directamente desde Javascript. He estado buscando por todos lados, pero todavía no puedo tener algo funcionando. Supuse que debía construir el enveloppe SOAP (ver a continuación). También uso jQuery.Cómo llamar a SOAP WS desde Javascript/jQuery

En primer lugar, ¿me aseguraría de poder llamar a un servicio web SOAP ubicado en otro lugar? es decir, no hay ninguna limitación, como la limitación de dominio cruzado.

Además, no estoy seguro de cuál es la URL correcta que necesito usar, el servicio SOAP se expone usando Ladon, para fines de depuración he comprobado que la WS funciona bien con soapUI, y aquí están las URL que puedo encontrar:

  • URL WSDL: // http://192.168.1.5/ws/MyWS/soap/description de mi comprensión no puede ser éste
  • servicio criterios de valoración: http://192.168.1.5/ws/MyWS/soap
  • SOAPAction: http://192.168.1.5/ws/MyWS/soap/myOperation

Creo que debería usar punto final o SOAPAction pero no funcionó. Puedo perder algo aquí o el Javascript posterior es tan defectuoso que no puedo estar seguro.

Ahora aquí es mi real JS hacer la llamada (hay algunas preguntas dentro de los comentarios):

<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://stackoverflow.com/questions/11916780/changing-getjson-to-jsonp?rq=1 

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

</script> 

<body> 

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

</body> 
</html> 

mejores deseos

EDIT: sin dejar de tratar de buscar una respuesta, tengo reveló que =>Simplest SOAP example donde Prestaul dice "Esto no se puede hacer con JavaScript directo a menos que el servicio web esté en el mismo dominio que su página". Entonces, ¿tal vez estoy tratando de hacer algo imposible? ¿Es esta la razón por la que no puede funcionar?

Respuesta

20

No puede enviar solicitudes AJAX de dominios cruzados debido a la restricción same origin policy que está incorporada en los navegadores. Para hacer esto, su página HTML que contiene el código jQuery debe estar alojada en el mismo dominio que el servicio web (http://192.168.1.5/ws/MyWS/).

Existen soluciones que implican el uso de JSONP en el servidor, pero dado que su servicio web es SOAP, esto no puede funcionar.

La única forma confiable de hacerlo funcionar si no puede mover su javascript en el mismo dominio que el servicio web es compilar un script del lado del servidor que se alojará en el mismo dominio que el código de JavaScript y que actuará como un puente entre los 2 dominios. Entonces enviaría una solicitud AJAX a su secuencia de comandos del lado del servidor que a su vez invocará el servicio web remoto y devolverá el resultado.

+0

gracias, así que era un error pensar que el uso de jabón con un cliente completo JS era un trabajo alrededor. Y sí, he probado el código que puse arriba, funciona cuando se usa desde el mismo servidor. Por cierto, también necesitaré que otros servidores puedan hacerlo ... voy a echar un vistazo a la forma en que sugieres. – user1340802

1

El código siguiente está funcionando bien. Puede ser que pueda ayudarte.

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

    }); 
+2

que no funciona – Mukus

+0

no va a funcionar .. –

8

¿Qué le parece esto? https://github.com/doedje/jquery.soap

Parece bastante fácil. Tal vez te ayude.

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> 
+0

con el archivo SVC como https: // localhost: 1303/BbsService.svc cómo podemos utilizarlo? – arslanaybars

Cuestiones relacionadas