如何在ajax请求中将xml标记作为参数发送?

时间:2019-07-12 01:20:10

标签: javascript jquery ajax xml

我在将XML标签作为Ajax请求中的参数发送时遇到问题

起初,我尝试将其作为字符串发送,但是请求失败,因为ajax将标签编码为“&-lt; Id&-gt; 16385&-lt; / Id&-gt;”, 所以我已经使用jquery将其转换为xmlDoc,请求也失败了。 这是我的代码示例,您还会在下面找到请求有效负载。

let id='<Id>16385</Id>';

  xmlDoc = $.parseXML( id );
  $xml = $( xmlDoc );
  id = $xml.find( "Id" )[0];
  let obj={
    method: "ReadMOD_SYS_OC_entity_unit",
    namespace:
      "http://schemas/comassetegOrganizationChart/MOD_SYS_OC_entity_unit/operations",
    param :{
      "MOD_SYS_OC_entity_unit-id":id,
       MOD_SYS_OC_entity_Name:"Test"
    } 
  }
  cordys.cordysAjax(obj.method,obj.namespace,obj.param).done(function(response) {
      console.log(response);
  });

function cordysAjax(method,namespace,par) {
    return $.cordys.ajax({
      method: method,
      namespace:namespace,
      parameters: par,
      type: 'POST',
      contentType: "xml"
    });
}


**when sending the parameter as string**

 <SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'><SOAP:Body><ReadMOD_SYS_OC_entity_unit xmlns='http://schemas/comassetegOrganizationChart/MOD_SYS_OC_entity_unit/operations' ><MOD_SYS_OC_entity_unit-id>&'lt;Id&gt;16385&'lt;/Id&'gt;</MOD_SYS_OC_entity_unit-id><MOD_SYS_OC_entity_Name>Test</MOD_SYS_OC_entity_Name></ReadMOD_SYS_OC_entity_unit></SOAP:Body></SOAP:Envelope>

 **When sending the parameter as XML**

    <SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'><SOAP:Body><ReadMOD_SYS_OC_entity_unit xmlns='http://schemas/comassetegOrganizationChart/MOD_SYS_OC_entity_unit/operations' ><MOD_SYS_OC_entity_unit-id/><MOD_SYS_OC_entity_Name>Test</MOD_SYS_OC_entity_Name></ReadMOD_SYS_OC_entity_unit></SOAP:Body></SOAP:Envelope>

2 个答案:

答案 0 :(得分:0)

XML提供了CDATA部分,以包含可能包含保留字符的字符串

<![CDATA[<Id>16385</Id>]]>

您的XML可能是

<?xml version="1.0"?>
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP:Body>
    <ReadMOD_SYS_OC_entity_unit xmlns="http://schemas/comassetegOrganizationChart/MOD_SYS_OC_entity_unit/operations">
      <MOD_SYS_OC_entity_unit-id><![CDATA[<Id>16385</Id>]]></MOD_SYS_OC_entity_unit-id>
      <MOD_SYS_OC_entity_Name>Test</MOD_SYS_OC_entity_Name>
    </ReadMOD_SYS_OC_entity_unit>
  </SOAP:Body>
</SOAP:Envelope>

答案 1 :(得分:0)

答案是我不必像``16385''一样将第一个参数的值作为xml标签发送 正确的答案是

 param :{
      "MOD_SYS_OC_entity_unit-id":{Id:16385},
       MOD_SYS_OC_entity_Name:"Test"
    } 

Ajax将像这样格式化请求有效负载

<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'>
<SOAP:Body>
    <ReadMOD_SYS_OC_entity_unit xmlns='http://schemas/comassetegOrganizationChart/MOD_SYS_OC_entity_unit/operations' >
        <MOD_SYS_OC_entity_unit-id>
            <Id>16385</Id>
        </MOD_SYS_OC_entity_unit-id>
    </ReadMOD_SYS_OC_entity_unit>
</SOAP:Body>