简体   繁体   English

从Iron-Form格式化JSON数据

[英]Formatting JSON data from iron-form

I'm using iron-form to send data to a Rails server. 我正在使用铁表格将数据发送到Rails服务器。 Currently the form is sending JSON similar to this: 当前,表单正在发送类似于以下内容的JSON:

{
  "date": "January 1",
  "name": "John Doe",
  "company": "Whatever Inc."
}

But in order to receive it on the Rails end I need it to be formatted like this: 但是为了在Rails端接收它,我需要将其格式化为:

{
  "userInfo": {
    "date": "January 1",
    "name": "John Doe",
    "company": "Whatever Inc."
  }
}

How do I nest the form data within the userInfo param? 如何将表单数据嵌套在userInfo参数中? I tried using the iron-form-presubmit event listener but couldn't make it work. 我尝试使用iron-form-presubmit事件侦听器,但无法使其正常工作。

Here is the code for my iron-form: 这是我的铁表格的代码:

<form is="iron-form" id="form" method="post" action="url/for/api">
  <input name="date" is="iron-input">
  <input name="name" is="iron-input">
  <input name="company" is="iron-input">

  <div id="buttons">
    <paper-button id="submit" raised onclick="_submit(event)">Save</paper-button>
    <paper-button id="reset" raised onclick="_reset(event)">Reset </paper-button>
  </div>
</form>

And the javascript: 和javascript:

<script>

Polymer({
  is: 'my-view1',
});

function _submit(event) {
    var form = Polymer.dom(event).localTarget.parentElement.parentElement;
    form.submit();
}

function _reset(event) {
    var form = Polymer.dom(event).localTarget.parentElement.parentElement;
    form.reset();
}

</script>

from my understanding you could update the request body before the data gets submitted and transform the current data into an object/structure of your liking: 据我了解,您可以在数据提交之前更新请求主体,并将当前数据转换为您喜欢的对象/结构:

<form is="iron-form" on-iron-form-presubmit="_presubmit" id="form" method="post" action="url/for/api">
  <input name="date" is="iron-input">
  <input name="name" is="iron-input">
  <input name="company" is="iron-input">

  <div id="buttons">
    <paper-button id="submit" raised onclick="_submit(event)">Save</paper-button>
    <paper-button id="reset" raised onclick="_reset(event)">Reset </paper-button>
  </div>
</form>

similar to how its done here , but changing the body entirely 类似于此处的操作 ,但完全改变了身体

function _presubmit(e) {
  let body = this.$.form.request.body;
  body = {"userInfo" : body };
}

Hope this helps a lil. 希望这会有所帮助。

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

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