2014-09-25 50 views
1

举例来说,如果我有我的index.html文件里面自动绑定模板下面的代码:如何通过javascript访问core-ajax响应数据?

的index.html

<template is="auto-binding"> 
    <core-ajax id="ds" auto url="url/to/data.json" response="{{data}}"></core-ajax> 
    <my-items items="{{data}}"></my-items> 
</template> 

app.js

(function(document) { 
    'use strict'; 

    document.addEventListener('polymer-ready', function() { 
     var responseData = ???? 
    }); 
})(wrap(document)); 
+0

这是在一个聚合物元素或只是在主html文件?你打算如何处理这个响应在html或javascript中使用它? – 2014-09-25 14:11:11

+0

上面的代码位于自动绑定模板中的主HTML文件中。我打算使用JavaScript/jQuery的数据。 – 2014-09-25 14:12:19

回答

2

通常情况下,我们使用数据绑定与核心ajax,但如果你需要得到它与J​​S你可以得到的答复出core-response事件core-ajax发生火灾,或者您可以查看core-ajax标记本身的response属性。 jsbin example

<core-ajax auto url="http://date.jsontest.com"></core-ajax> 

<script> 
    document.addEventListener('polymer-ready', function() { 
    var ajax = document.querySelector('core-ajax'); 
    ajax.addEventListener('core-response', function(e) { 
     console.log(e.detail.response); 
     // or 
     console.log(e.target.response); 
     // or 
     console.log(ajax.response); 
    }); 
    }); 
</script> 

编辑:OP希望得到在汽车内结合核心的Ajax元素模板

你应该听由auto-binding模板触发的template-bound事件时戳其内容的页。那么你可以querySelectorcore-ajaxjsbin example

<template is="auto-binding"> 
    <core-ajax auto url="http://date.jsontest.com"></core-ajax> 
</template> 

<script> 
    var tmpl = document.querySelector('template'); 
    tmpl.addEventListener('template-bound', function() { 
    var ajax = document.querySelector('core-ajax'); 
    ajax.addEventListener('core-response', function(e) { 
     console.log(e.detail.response); 
     // or 
     console.log(e.target.response); 
     // or 
     console.log(ajax.response); 
    }); 
    }); 
</script> 

编辑:为了展示一个更好的办法

由于原来的海报是专门询问有关获取使用JavaScript的反应,我给了JS完全办法。你可以使用绑定来清理它。 jsbin example

<template is="auto-binding"> 
    <core-ajax auto 
      response="{{data}}" 
      on-core-response="{{ajaxHandler}}" 
      url="http://date.jsontest.com" 
      handleAs="json"></core-ajax> 
    <h1>{{data.date}}: {{data.time}}</h1> 
</template> 

<script> 
    addEventListener('template-bound', function(e) { 
    // do something else with response 
    e.target.ajaxHandler = function(event) { 
     console.log(event.target.response); 
    } 
    }); 
</script> 
+1

Uncaught TypeError:无法读取null的属性'addEventListener' – 2014-09-25 14:19:38

+0

尝试通过id获取core-ajax var ajax = document.querySelector(“#ds”); – 2014-09-25 14:21:23

+0

ajax仍为空:( – 2014-09-25 14:22:54