简体   繁体   English

使用JavaScript将XML发布到Web服务

[英]POST XML to web service with javascript

I am new with javascript, need help to post data to web service. 我是javascript新手,需要帮助才能将数据发布到Web服务。 I have simple page: 我有简单的页面:

        <form action="#" class="simple-form">
            <input id="A" type="text" autocomplete="off">
            <input id="B" type="text" autocomplete="off">
            <input id="amount" type="text" autocomplete="off">
        </form>
        <button align="middle" class="button1" id="create" 
                           onclick="f1()">Create</button>

I need to get values of input A, B and amount, then pass them to url: " http://localhost:8080/dopayment/ " with POST in xml format. 我需要获取输入A,B和金额的值,然后将它们传递给url:“ http:// localhost:8080 / dopayment / ”,并使用xml格式的POST。 The exact xml format must be: 确切的xml格式必须为:

<Payment>
    <a>xxx</a>
    <b>xxx</b>
    <amount>xx</amount>
</Payment>

PS from Postman I have checked above given XML with post to given URL, it is working. 来自Postman的PS我已经检查了上面给定的XML和到给定URL的发布,它正在工作。

Thanks in advance to everyone. 在此先感谢大家。

Since you create the form, put button into it to trigger submit event. 自创建表单以来,将按钮放入表单以触发Submit事件。

 <form action="#" class="simple-form">
        <input id="A" type="text" autocomplete="off">
        <input id="B" type="text" autocomplete="off">
        <input id="amount" type="text" autocomplete="off">
        <input type="submit" align="middle" class="button1" value="Create">        
 </form>

You can sent info by AJAX, this way: 您可以通过AJAX通过以下方式发送信息:

document.getElementsByClassName("simple-form")[0].addEventListener('submit', (e) => {
  e.preventDefault();
  const formData = new FormData(e.target);
  const data = `<Payment>
   <a>${formData.get('A')}</a>
   <b>${formData.get('B')}</b>
   <amount>${formData.get('amount')}</amount>
  </Payment>`;

  fetch('http://example.com', {
    method: 'POST', // or 'PUT'
    body: data, // data can be `string` or {object}!
    headers:{
      'Content-Type': 'application/xml'
    }
  }).then(res => res.json())
  .catch(error => console.error('Error:', error))
  .then(response => console.log('Success:', response));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM