它是一个非常基本的模块化结构的java脚本,基本上我试图做的是,通过API请求随机引用,通过Mustache.js将它们打印在HTML页面上。之前没有使用模块化结构的方式,我设法完成了这项任务,但我也想尝试模块化的方式。如何通过模块化js结构中的ajax调用接收数据?
我现在面临的问题是,每当我尝试呈现我的数据(即报价+作者),我在我的控制台上收到错误,该函数未定义。
请检查我的代码〜
(function(){
var quoting ={
quotei : [],
template : $("#quoteTemplate").html(),
init: function(){
this.cacheDom();
this.bindEvents();
this.createQuote();
this.recieve();
this.renderx();
},
cacheDom: function(){
this.$el = $('#quotez');
this.$button = this.$el.find('button');
this.$template = this.$el.find('#quoteTemplate').html();
},
bindEvents: function(){
this.$button.on('click',this.createQuote.bind(this));
},
renderx: function(data){
this.$el.html(Mustache.render(this.template,data));
},
createQuote: function(){
$.ajax({
url:'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
type:'GET',
data:{},
dataType:'json',
success : function(data){;
this.render(data)
},
beforeSend: function(xhr){
xhr.setRequestHeader("X-Mashape-Authorization","cvkQkHJurZmshuIhXxwXzIjBchHVp1yk0rDjsnNambAJ9duu7v");
}
});
},
};
quoting.init();
})()
请帮我和原谅任何错误,因为这是我第一次张贴在计算器上。
两点退房 - 在你的成功函数,你调用'this.render()'但拼写'renderx()'在这之前...最可能的错误?另外,请记住,在'成功'手中,'this'指的是xhr对象,而不是你的外部函数。你需要绑定相应的'this'才能工作。 – mherzig