Polymer 1.x:在自定义行为中使用iron-ajax

时间:2017-03-13 05:46:24

标签: ajax polymer polymer-1.0 polymer-1.x iron-elements

我正在构建自定义行为。称之为MyBehaviors.MySpecialBehavior

但是我需要获取本地存储在名为my-data.json的JSON文件中的数据。

我怎样才能在我的行为中做到这一点?我正在尝试导入iron-ajax,但我想不出如何访问其方法或属性。

我-特殊behavior.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">

<script>
  var MyBehaviors = MyBehaviors || {};
  MyBehaviors.MySpecialBehaviorImpl = {
    // Methods go here that rely on data at my-data.json
  };

  MyBehaviors.MySpecialBehavior = [
    MyBehaviors.MySpecialBehaviorImpl,
  ];
</script>
我-data.json
{
  "important": "data",
  "j": 5,
  "o": "N",
  "goes": "here"
}

2 个答案:

答案 0 :(得分:3)

您可以以编程方式创建元素。看看 iron-ajax 本身如何在内部使用 iron-request

https://github.com/PolymerElements/iron-ajax/blob/master/iron-ajax.html#L442

请参阅您的用例,即用户 a1626创建了此代码段:

var ajax = document.createElement('iron-ajax');
ajax.contentType = "application/json";
ajax.handleAs = "json";
ajax.url = <url goes here>
ajax.method = 'get';
ajax.addEventListener('response', function (event) {
    //response handler                  
});
ajax.generateRequest();

答案 1 :(得分:1)

您可以在添加的事件侦听器中使用ajax.lastResponse访问json数据。

var ajax = document.createElement('iron-ajax');
ajax.contentType = "application/json";
ajax.handleAs = "json";
ajax.url = <url goes here>
ajax.method = 'get';
ajax.addEventListener('response', function (event) {
    //response handler
    console.log('ajax', ajax.lastResponse);            
});
ajax.generateRequest();