简体   繁体   中英

Formatting JSON data from iron-form

I'm using iron-form to send data to a Rails server. Currently the form is sending JSON similar to this:

{
  "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:

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

How do I nest the form data within the userInfo param? I tried using the iron-form-presubmit event listener but couldn't make it work.

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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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