首页 > 解决方案 > How to send an XML file to API by javascript

问题描述

I am reporting to you today with a polite notification of me being directed, which I am kindly doing when trying to send an API request. Yes, I know, there is a right to provide information about JS / AJAX / JQuery on the net, although it usually concerns reading API, so it is available for one API function. Below is the code:

Of course, I changed the API key on purpose, so that's not a problem, the key itself is fine. ;)

<script>
UserAction () {
    var xhr = new XMLHttpRequest ();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
           // Common Action To Take When Document is ready:
            var answer = xhr.responseText;
            console.log ("ok" + response);
        }
    };
    xhr.open ('POST', 'https: //api5.esv2.com/v2/Api/Subscribers/', true);

    xhr.send ("POST https://api5.esv2.com/v2/Api/Subscribers/ HTTP / 1.1 Content-Type: text / xml <ApiRequest xmlns: xsi = \" http://www.w3.org/ 2001 / XMLSchema-instance \ "xmlns: xs = \" http: //www.w3.org/2001/XMLSchema \ "> <ApiKey> KEY </ApiKey> <xsi data: type = \" Subscriber \ "> < Mode> AddAndUpdate </Mode> <Force> true </Force> <ListId> 1 </ListId> <Email> jan.kowalski@domena.com </Email> <Firstname> Jan </Firstname> <Lastname> Kowalski < /Lastname><TrackingCode>123</TrackingCode><Vendor>xyz</Vendor><Ip>11.22.33.44</Ip><Properties><Property><Id>5</Id><Value xsi: type = \ "xs: string \"> student </Value> </Property> <Property> <Id> 3 </Id> <Value xsi: type = \ "xs: dateTime \"> 1985-03-12 </Value> </Property></Properties></Data> </ApiRequest> ");

}

标签: javascriptapirestpost

解决方案


您需要正确设置标头并仅在send.

xhr.open ('POST', 'https://api5.esv2.com/v2/Api/Subscribers/', true);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.send(XMLbody);

取决于情况(您期望什么样的响应),您可能也需要更改这部分。

var answer = xhr.responseXML;

推荐阅读