如何通过纸张按钮点击触发iron-ajax请求?

时间:2015-10-26 11:36:09

标签: javascript html ajax polymer

当我点击<iron-ajax>元素时,我希望从POST<textarea> http://example.net <paper-button>动态数据:

&#13;
&#13;
function get_data() {
  return {content:document.getElementById("mycontent").html()}
}
&#13;
<html>
  <head>
    <!-- Imports-->
  </head>
  <body>
    <iron-ajax
      url="//example.net"
    ></iron-ajax>
    <paper-button id="mybutton"></paper-button>
    <textarea id="mycontent"></textarea>
  </body>
</html>
&#13;
&#13;
&#13;

如何合并iron-ajaxpaper-button元素以将数据发送到服务器?

3 个答案:

答案 0 :(得分:7)

您需要将聚合物元素包裹在将注册为聚合物元素的标签中。您可以在案例中使用dom-bind

<template id="t" is="dom-bind">           
    <textarea value="{{dataToPost::input}}"></textarea>
    <paper-button on-tap="postData">Post Data</paper-button>
    <iron-ajax 
    id="dataAjax" 
    method="post"
    url="data/url"
    on-response="postComplete"></iron-ajax>
</template>  

在脚本中,您需要在generateReqeust元素上调用iron-ajax

(function (document) {
'use strict';
document.addEventListener('WebComponentsReady', function() {

    // We have to bind the template with the model
    var t = document.querySelector('#t');
    var ajaxRequest = t.$.dataAjax;

    // make the iron-ajax call
    t.postData = function() {
      ajaxRequest.body = {
        'text': t.dataToPost;
      } 
      ajaxRequest.generateRequest();
    }

    //callback on request complete
    t.postComplete = function(){
      alert('whoa! request complete');
    }
});
})(document);

GEThttp://plnkr.co/edit/13QJ7QFETIBg4bEiCMS7?p=preview

的工作人员

答案 1 :(得分:1)

最简单和最便宜的方法是只查询铁ajax元素并调用方法generateRequest()

将其放在您的on-tap处理程序中,以便用于纸张按钮...

Polymer.dom(this.root).querySelector('iron-ajax').generateRequest()

答案 2 :(得分:0)

如果你热衷于不使用<template is="dom-bind">(它会使它变得容易得多),你可以采用普通的香草路线(即没有dom-bind)。

&#13;
&#13;
<html>

<head>
  <!-- Imports-->
</head>

<body>
  <iron-ajax url="//example.net"></iron-ajax>
  <paper-button id="mybutton"></paper-button>
  <textarea id="mycontent"></textarea>
  <script>
    window.addEventListener('WebComponentsReady', function() {
      var ironAjax = document.querySelector('iron-ajax');
      ironAjax.method = 'post';
      ironAjax.contentType = 'text/plain'; // you're just sending text
      var myButton = document.getElementById('mybutton');
      var myContent = document.getElementById('mycontent');

      myButton.addEventListener('tap', function(e) {
        var valueToSend = myContent.value;
        ironAjax.body = valueToSend;
        ironAjax.generateRequest();
      });
    });
  </script>
</body>

</html>
&#13;
&#13;
&#13;