为什么我不能在ajax成功返回时访问render函数?也许我疯了但我以前做过这个.
它告诉我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;
}
};
Run Code Online (Sandbox Code Playgroud)
尝试呼叫时,范围已更改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);
}
});
},
Run Code Online (Sandbox Code Playgroud)
编辑:我错了,在成功函数中this变量包含ajax请求的选项,但是我的解决方案仍然是正确的.在jQuery文档中查看更多内容(http://docs.jquery.com/Ajax/jQuery.ajax#options)