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

只谈情不闲聊 提交于 2019-12-07 00:09:05

问题


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 :)


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/30295236/polymer-iron-ajax-how-to-bind-data-from-input-element-to-iron-ajaxs-body-attr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!