简体   繁体   English

聚合物1.x:在自定义行为中使用铁制ajax

[英]Polymer 1.x: Using iron-ajax inside a custom behavior

I'm building a custom behavior. 我正在建立自定义行为。 Call it MyBehaviors.MySpecialBehavior . 将其MyBehaviors.MySpecialBehavior

But I need to get data that's stored locally in a JSON file called my-data.json . 但我需要获取本地存储在名为my-data.json的JSON文件中的数据。

How can I do this inside my behavior? 如何在我的行为中做到这一点? I'm trying to import iron-ajax but I can't think of how to access its methods or properties. 我正在尝试导入iron-ajax但是我iron-ajax来如何访问其方法或属性。

my-special-behavior.html my-special-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> 
my-data.json my-data.json
 { "important": "data", "j": 5, "o": "N", "goes": "here" } 

You can create elements programatically. 您可以以编程方式创建元素。 Have a look at how iron-ajax itself does that to use iron-request internally: 看看iron-ajax本身如何在内部使用iron-request

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

Refering to your usecase, the user a1626 created this snippet: 参考您的用例,用户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();

You can access the json data with ajax.lastResponse inside the added event listener. 您可以在添加的事件监听器中使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM