题
我已经挖掘到聚合物的ajax核心元素,像下面这样的代码工作正常:
<core-ajax url="./ajax-test.txt" auto response="{{resp}}"></core-ajax>
<textarea value="{{resp}}"></textarea>
我可以从 {{resp}}
在这种情况下。我已经深入研究了core-ajax源代码,并了解它是如何完成的:
- 使
response
通过设置发布的属性attributes="response ..."
- 将ajax响应传递给
this.response
然后我试图建立我自己的ajax组件,但它没有工作,我的ajax组件代码是:
Polymer('louis-ajax', {
url: '',
response: null,
ready: function() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
this.response = xmlhttp.responseText;
}
}.bind(this);
xmlhttp.open("GET",this.url,true);
xmlhttp.send();
}
});
而我的应用程序代码是这样的:
<louis-ajax url="http://polymer.snspay.cn/api/posts.json" response="{{response}}"></louis-ajax>
<span>We have got the ajax response as</span> : <input type='text' value="{{response}}" />
结果是ajax请求已经成功完成,但是input的值是"{{response}}",而不是{{response}}的值,所以我认为我理解发布的属性的工作方式有问题,有什么帮助吗?Thk。
解决方案
我知道你说你想通了,但对于其他人来这个页面寻找一个完全有效的解决方案和解释,这里是。
如果您想要数据绑定而无需创建自定义元素,则必须将代码放入具有 is
属性设置为 auto-binding
:
<template is="auto-binding">
<core-ajax url="./ajax-test.txt" auto response="{{resp}}"></core-ajax>
<textarea value="{{resp}}"></textarea>
</template>
如果没有这个,你就不会知道它需要在你的html中连接绑定,等等 {{resp}}
将被视为文本。
更详细的解释可以在这里找到: http://www.polymer-project.org/docs/polymer/databinding-advanced.html#autobinding
不隶属于 StackOverflow