当ajax成功返回时,为什么不能访问渲染功能?也许我快疯了,但我以前做过。
它告诉我this.render不是函数吗?
DataItem.prototype = {
display: function () {
$('body').append(this.name + ": " + this.getData(this.rootData, this.subData) + "<br />");
},
getData: function (rootData, subData) {
$.ajax({
type: "GET",
url: "json/data.js",
data: "",
dataType: "json",
success: function (json){
this.render(json);
}
});
},
render: function (json) {
var res = [];
for(var i=0, t; t=json.log.entries[i]; i++) {
var p = t.request.url;
if (p!=undefined) res.push(p);
}
return res.length;
}
};
最佳答案
当您尝试调用this.render()
时,范围已更改。我相信this
包含ajax请求对象而不是DataItem
对象。
一个简单的解决方案是这样的:
getData: function (rootData, subData) {
var self = this;
$.ajax({
type: "GET",
url: "json/data.js",
data: "",
dataType: "json",
success: function (json){
self.render(json);
}
});
},
编辑:我错了,在成功函数中,
this
变量包含ajax请求的选项,但是我的解决方案仍然正确。在jQuery文档(http://docs.jquery.com/Ajax/jQuery.ajax#options)中查看更多