0

背景:我正在通过 ajax 从外部 php 文件插入页面内容。
约束:我想遵循如何在 JavaScript 中“正确”创建自定义对象中描述的对象结构?.
问题:但是连同这个结构,我没有在成功回调中收到响应数据。在萤火虫中,我可以看到邮寄返回的正确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 外部回调函数
JavaScript: var functionName = function() {} vs function functionName() {}
如果不想在调用 $.ajax( )?
jQuery ajax 成功回调函数定义

简单的代码组织(这行得通!)

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
    });
  });
4

1 回答 1

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
    });
};
于 2013-05-18T00:12:45.873 回答