سؤال

ما هو أبسط مثال على SOAP باستخدام Javascript؟

لكي تكون الإجابة مفيدة قدر الإمكان، يجب أن:

  • أن تكون وظيفية (وبعبارة أخرى تعمل بالفعل)
  • أرسل معلمة واحدة على الأقل يمكن تعيينها في مكان آخر في الكود
  • قم بمعالجة قيمة نتيجة واحدة على الأقل يمكن قراءتها في مكان آخر في الكود
  • العمل مع معظم إصدارات المتصفح الحديثة
  • كن واضحًا ومختصرًا قدر الإمكان، دون الاستعانة بمكتبة خارجية
هل كانت مفيدة؟

المحلول

هذا هو أبسط عميل 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 -->

نصائح أخرى

هناك العديد من المراوغات في الطريقة التي تتعامل بها المتصفحات مع XMLHttpRequest، وسيعمل رمز JS هذا عبر جميع المتصفحات:
https://github.com/ilinsky/xmlhttprequest

يقوم رمز JS هذا بتحويل XML إلى كائنات JavaScript سهلة الاستخدام:
http://www.terracoder.com/index.php/xml-objectifier

يمكن تضمين رمز 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...

خياران آخران:

لا يمكن القيام بذلك باستخدام جافا سكريبت المباشر إلا إذا كانت خدمة الويب موجودة في نفس مجال صفحتك. يحرر:في عام 2008 وفي IE <10، لا يمكن القيام بذلك باستخدام جافا سكريبت المباشر إلا إذا كانت الخدمة في نفس المجال مثل صفحتك.

إذا كانت خدمة الويب موجودة في مجال آخر [ويجب عليك دعم IE<10]، فسيتعين عليك استخدام صفحة وكيل على المجال الخاص بك والتي ستقوم باسترداد النتائج وإعادتها إليك.إذا لم تكن بحاجة إلى دعم IE القديم، فأنت بحاجة إلى إضافة دعم CORS إلى خدمتك.في كلتا الحالتين، يجب عليك استخدام شيء مثل lib الذي اقترحه timyates لأنك لا تريد أن تضطر إلى تحليل النتائج بنفسك.

إذا كانت خدمة الويب موجودة في نطاقك الخاص، فلا تستخدم SOAP.لا يوجد سبب وجيه للقيام بذلك.إذا كانت خدمة الويب موجودة في نطاقك الخاص، فقم بتعديلها حتى تتمكن من إرجاع JSON وتوفير نفسك عناء التعامل مع جميع المتاعب التي تأتي مع SOAP.

الإجابة المختصرة هي:لا تقدم طلبات SOAP من جافا سكريبت.استخدم خدمة ويب لطلب بيانات من مجال آخر، وإذا قمت بذلك، فقم بتحليل النتائج على جانب الخادم وإعادتها في نموذج JS سهل الاستخدام.

يمكنك استخدام ال jquery.soap البرنامج المساعد للقيام بهذا العمل نيابة عنك.

يستخدم هذا البرنامج النصي $.ajax لإرسال SOAPEnvelope.يمكن أن يستغرق XML DOM أو سلسلة XML أو JSON كمدخل ويمكن إرجاع الاستجابة إما XML DOM أو سلسلة XML أو JSON أيضًا.

مثال للاستخدام من الموقع:

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

هل هناك اي احد جرب هذة؟ 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>

توماس:

يُفضل JSON للاستخدام في الواجهة الأمامية لأنه جافا سكريبت.لذلك ليس لديك XML للتعامل معه.يعد SOAP أمرًا مؤلمًا بدون استخدام مكتبة بسبب هذا.ذكر أحدهم SOAPClient، وهي مكتبة جيدة، بدأنا بها في مشروعنا.ومع ذلك، كان بها بعض القيود وكان علينا إعادة كتابة أجزاء كبيرة منها.لقد تم إصداره كـ SOAPjs ويدعم تمرير كائنات معقدة إلى الخادم، ويتضمن بعض نماذج رموز الوكيل لاستهلاك الخدمات من المجالات الأخرى.

<html>
 <head>
    <title>Calling Web Service from jQuery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnCallWebService").click(function (event) {
                var wsUrl = "http://abc.com/services/soap/server1.php";
                var soapRequest ='<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:impl="http://abc.com/services/soap/server1.php">  <symbol>' + $("#txtName").val() + '</symbol>   </getQuote> </soap:Body></soap:Envelope>';
                               alert(soapRequest)
                $.ajax({
                    type: "POST",
                    url: wsUrl,
                    contentType: "text/xml",
                    dataType: "xml",
                    data: soapRequest,
                    success: processSuccess,
                    error: processError
                });

            });
        });

        function processSuccess(data, status, req) { alert('success');
            if (status == "success")
                $("#response").text($(req.responseXML).find("Result").text());

                alert(req.responseXML);
        }

        function processError(data, status, req) {
        alert('err'+data.state);
            //alert(req.responseText + " " + status);
        } 

    </script>
</head>
<body>
    <h3>
        Calling Web Services with jQuery/AJAX
    </h3>
    Enter your name:
    <input id="txtName" type="text" />
    <input id="btnCallWebService" value="Call web service" type="button" />
    <div id="response" ></div>
</body>
</html>

سماع هو أفضل برنامج تعليمي لجافا سكريبت مع SOAP مع مثال.

http://www.codeproject.com/Articles/12816/JavaScript-SOAP-Client

بعض الأمثلة الرائعة (وعميل JavaScript SOAP الجاهز!) هنا:http://plugins.jquery.com/soap/

تحقق من الملف التمهيدي، واحذر من قيود المتصفح ذات المصدر نفسه.

يمكنك بسهولة استخدام خدمات SOAP Web باستخدام JavaScript -> القائمة ب

function fncAddTwoIntegers(a, b)
{
    varoXmlHttp = new XMLHttpRequest();
    oXmlHttp.open("POST",
 "http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'",
 false);
    oXmlHttp.setRequestHeader("Content-Type", "text/xml");
    oXmlHttp.setRequestHeader("SOAPAction", "http://tempuri.org/AddTwoIntegers");
    oXmlHttp.send(" \
<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> \
    <AddTwoIntegers xmlns='http://tempuri.org/'> \
      <IntegerOne>" + a + "</IntegerOne> \
      <IntegerTwo>" + b + "</IntegerTwo> \
    </AddTwoIntegers> \
  </soap:Body> \
</soap:Envelope> \
");
    return oXmlHttp.responseXML.selectSingleNode("//AddTwoIntegersResult").text;
}

قد لا يلبي هذا جميع متطلباتك ولكنه يمثل بداية للإجابة على سؤالك فعليًا.(لقد تحولت XMLHttpRequest() ل ActiveXObject("MSXML2.XMLHTTP")).

أبسط مثال يتكون من:

  1. الحصول على مدخلات المستخدم.
  2. إنشاء رسالة 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>
    
  3. نشر الرسالة إلى عنوان url لخدمة الويب باستخدام XHR

  4. تحليل استجابة XML SOAP الخاصة بخدمة الويب مشابه لهذا

    <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>
    
  5. عرض النتائج للمستخدم.

ولكن هناك الكثير من المتاعب بدون مكتبات جافا سكريبت الخارجية.

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

قاعدة التفاف Angularjs $http XMLHttpRequest.طالما أن مجموعة محتوى الرأس ستفي بالكود التالي.

"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;

    }

}

السؤال هو "ما هو أبسط مثال لـ SOAP باستخدام Javascript؟"

هذه الإجابة هي مثال في Node.js البيئة، بدلا من المتصفح.(دعنا نسمي البرنامج النصي Soap-node.js) وسنستخدمه خدمة الويب SOAP العامة من Europe PMC كمثال للحصول على قائمة مراجع المقالة.

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.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top