javascript - 如何在单击纸质按钮时触发 iron-ajax 请求?

标签 javascript html ajax polymer

我想要<iron-ajax>POST来自 <textarea> 的动态数据至 http://example.net当我点击 <paper-button>元素:

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

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

最佳答案

您需要将 polymer 元素包裹在一个将注册为 polymer 元素的标签中。您可以在您的案例中使用 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>  

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

(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);

GET 的工作插件:http://plnkr.co/edit/13QJ7QFETIBg4bEiCMS7?p=preview

关于javascript - 如何在单击纸质按钮时触发 iron-ajax 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33344783/

相关文章:

php - WordPress - Ajax 请求不断返回 0

javascript - PHP PDO 循环在 JS 和 PHP 中不同

javascript - 将函数与对象绑定(bind)到 jQuery 'change' 事件处理程序

javascript - 从存储在变量中的选项创建选择框

javascript - JavaScript 中继承的子对象共享相同的数组属性?

javascript - 有没有一种方法可以从翻转区域触发多个弹出窗口?

html - Google Chrome HTML 表单选择

javascript - AJAX get 请求将每个字母放入数组中

javascript - 使用定位器找不到元素 : By(partial link text, Solid Community)

javascript - 如何渲染 JavaScript 对象?