简体   繁体   中英

polymer iron-ajax : How to Bind data from input element to iron-ajax's body attribute

I recently have problems binding data from input element to iron-ajax's "body" attribute. When I used core-ajax on polymer 0.5, I can easily bind values like this:

<core-ajax
           id="ajax"
           method="POST" 
           contentType="application/json"
           url="{{url}}"   
           body='{"username":"{{username}}", "password":"{{password}}"}'
           handleAs="json"
           on-core-response="{{responseHandler}}">
</core-ajax>

Now I tried the same thing with iron-ajax. But it sends literally "{{username}}" and "{{password}}" instead of their values. Here is the code:

<iron-ajax
           id="ajax"
           method="POST" 
           contentType="application/json"
           url="{{url}}"   
           body='{"username":"{{username}}", "password":"{{password}}"}'
           handle-as="json"
           on-response="responseHandler">
</iron-ajax>

How to make it work? Thank you for your answers :)

You can declare a computed property for the ajax body. Like so

properties: {
    ...
    ajaxBody: {
        type: String,
        computed: 'processBody(username, password)'
    }
},
processBody: function(username, password) {
    return JSON.stringify({username: username, password:password});
}

And then adding it on iron-ajax

<iron-ajax ... body="{{ajaxBody}}"></iron-ajax>

Another option is to use Computed Bindings

Your code would look something like this:

<iron-ajax
       ...
       body="{{getAjaxBody(username, password}}}"
       >
</iron-ajax>
<script>
Polymer({
  .....
  getAjaxBody: function(username, password) {
    return JSON.stringify({username: username, password: password});
  }
})
</script>

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