简体   繁体   中英

Submit form values in JSON object

I'm working on learning polymer.js. At the moment I'm just working on a simple web app to sign a user in. Currently, whenever I submit my form it submits in this format shown below versus a complete JSON object.

{
  email: "email@email.com",
  password: "password"
}

instead of ...

{
  "email":"email@email.com",
  "password":"password"
}

Here is my code:

<form action="http://httpbin.org/post" method="post">

  <sign-in-input email="{{_email}}" password="{{_password}}"></sign-in-input>

  <input class = "paperbtn" type="submit" value="Sign in">

  <input name="email" value="[[_email]]" hidden>
  <input name="password" value="[[_password]]" hidden>

</form>

sign-in-input.html:

    <dom-module id="sign-in-input">
<template>
      <paper-input label = "Email" id = "email" required></paper-input>
      <paper-input label = "Password" id = "password" required></paper-input>
</template>

<script>
  Polymer({
    is: 'sign-in-input',

    properties: {
      email: {
        type: String,
        notify: true
      },
      password: {
        type: String,
        notify: true
      }
    },

    listeners: {
      'input': '_onInput'
    },

    _onInput: function() {
      this.email = this.$.email.value.trim();
      this.password = this.$.password.value.trim();
    }
  });
</script>

You're sending an object ( obj ) when you should send a string.

Have you used JSON.stringify(obj) on the object that you want to send?

Other things that you're not asking about.


_onInput: function() {
  this.email = this.$.email.value.trim();
  this.password = this.$.password.value.trim();
}

You should use this.set('email', this.$.email.value.trim() because this.set sends an event in Polymer to update the value. This isn't an issue now, but it can be in other elements if you continue to use this.[property] .


  <paper-input label = "Email" id = "email" required></paper-input>
  <paper-input label = "Password" id = "password" required></paper-input>

You can bind listeners to these right away, to avoid using:

listeners: {
  'input': '_onInput'
},

_onInput: function() {
  this.email = this.$.email.value.trim();
  this.password = this.$.password.value.trim();
}

It will look something like:

 <paper-input label="Email" id="email" value="{{email::input}}" required></paper-input>
 <paper-input label="Password" id="password" value="{{password::change}}" required></paper-input>

I used two kinds of Polymer listeners, input and change. You can use either.

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