SOAP на клиенте

SOAP (Simple Object Access Protocol) – это протокол обмена данными в распределённой вычислительной среде. Он вырос из XML-RPC (XML Remote Procedure Call – прокол обмена XML-сообщениями посредством HTTP).

Состоит из конверта:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
...
</soap>

, в котором есть секции header, body, fault:

<soap:Header>
...
</soap:Header>
 
<soap:Body>
...
  <soap:Fault>
  ...
  </soap:Fault>
</soap:Body>

На клиенте используется стандартные возможности JS, объект XMLHttpRequest (сокращённо XHR).

Пример использования на чистом JS:

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('done. use firebug/console to see network response');
      }
   }
}
 
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// ...

Пример использования с помощью плагина для jQuery:

$.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 не предполагает специальных знаний, кроме умения работы с XHR.

Теги: