簡體   English   中英

聚合物1.x:在自定義行為中使用鐵制ajax

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

我正在建立自定義行為。 將其MyBehaviors.MySpecialBehavior

但我需要獲取本地存儲在名為my-data.json的JSON文件中的數據。

如何在我的行為中做到這一點? 我正在嘗試導入iron-ajax但是我iron-ajax來如何訪問其方法或屬性。

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
 { "important": "data", "j": 5, "o": "N", "goes": "here" } 

您可以以編程方式創建元素。 看看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();

您可以在添加的事件監聽器中使用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