我只是不知道如何在ajax成功中调用另一种聚合物功能。
这是我的代码:
<script>
(function () {
// these variables are shared by all instances of app-globals
var firstName = "John";
function setData(data) {
firstName = data;
console.log("Data gesetzt:" + firstName);
}
Polymer({
ready: function () {
this.setTest("Example"); //Works
$.ajax({
async: false,
type: "GET",
url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from,
dataType: 'jsonp',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
this.setTest(); //Doesnt work
}
});
},
setTest: function () {
console.log("hi");
}
});
})();
</script>
来自success函数的控制台日志:Uncaught TypeError:undefined不是函数。
那么如何在回调中调用setTest:function(){}?
答案 0 :(得分:4)
您需要为jQuery ajax调用设置context选项,以便成功处理程序中的this
具有正确的值(它通常指向jqXHR对象):
Polymer({
ready: function () {
this.setTest("Example"); //Works
$.ajax({
// set the context option so this will have the desired value
// in the success handler
context: this,
async: false,
type: "GET",
url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from,
dataType: 'jsonp',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
this.setTest(); // should work now
}
});
},
setTest: function () {
console.log("hi");
}
或者,您可以将this
这样的值保存到另一个可以从回调中使用的变量中:
Polymer({
ready: function () {
// save this value into another variable so it can be used in callbacks
var self = this;
this.setTest("Example"); //Works
$.ajax({
async: false,
type: "GET",
url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from,
dataType: 'jsonp',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
self.setTest(); // should work now
}
});
},
setTest: function () {
console.log("hi");
}