后台:我通过ajax从外部php文件插入页面内容。
约束:我想遵循How to “properly” create a custom object in JavaScript?中描述的对象结构
问题:但是在这个结构中,我没有收到成功回调的响应数据。在firebug中,我可以看到post发回的正确的 html。
// Abstract class for functionality of both QuizView and QuizAdmin
Quiz = Object.makeSubclass();
Quiz.prototype._init= function() {};
Quiz.prototype.fetchSuccess= function(data) {
// fetchSuccess must be defined before fetch.
console.log("Quiz.prototype.fetchSucces"); // This gets printed out - so the function is called.
console.log(this.targetElement); // echoes the correct element - when I hoover it, I see it in the page.
console.log(data); // echoes undefined
this.targetElement.append(data); // Obviously this line is what I want to do.
};
//This function gets content specified by url.
Quiz.prototype.fetch= function(what,where) {
console.log("Quiz.prototype.fetch");
this.targetElement=where;
console.log(this.targetElement);
// Get the the content
$.ajax({
type: "POST",
url: what,
success: this.fetchSuccess,
targetElement: this.targetElement,
dataType: "html",
async: false
});
}; // End Quiz.prototype.fetch
注意:基本上,相关问题以及我的代码之间的唯一区别是我使用的是function expression
而不是function declaration
。这是因为我想遵循约束中描述的结构。
Jquery ajax external callback function
JavaScript: var functionName = function() {} vs function functionName() {}
Where to define a jQuery $.ajax() success function if you don't want to define in the call to $.ajax()?
jQuery ajax success callback function definition
function fetchSuccess(data){
$(".content-bottom").append(data);
}
$(document).ready(function(){
// Get the view content
$.ajax({
type: "POST",
url: "../../../../includes/quiz1/index.php",
success: fetchSuccess,
dataType: "html",
async: false
});
});
答案 0 :(得分:1)
试试这个
您正在传递函数参考,this
内的fetchSuccess
不是您所期望的
// Abstract class for functionality of both QuizView and QuizAdmin
Quiz = Object.makeSubclass();
Quiz.prototype._init= function() {};
Quiz.prototype.fetchSuccess= function(data) {
// fetchSuccess must be defined before fetch.
console.log("Quiz.prototype.fetchSucces"); // This gets printed out - so the function is called.
console.log(this.targetElement); // echoes the correct element - when I hoover it, I see it in the page.
console.log(data); // echoes undefined
this.targetElement.append(data); // Obviously this line is what I want to do.
};
//This function gets content specified by url.
Quiz.prototype.fetch= function(what,where) {
console.log("Quiz.prototype.fetch");
this.targetElement=where;
console.log(this.targetElement);
// Get the the content
var self = this;
$.ajax({
type: "POST",
url: what,
success: function(){self.fetchSuccess.apply(self, arguments)},
targetElement: this.targetElement,
dataType: "html",
async: false
});
};