0

次のようなJavascriptオブジェクトがあります。

var MyObject = {
   func1 : function() {
       // Does something
   },
   func2 : function() {
       // Send an AJAX request out
       $.post('', $('form').serialize(), function(response) {
           // Call the first function
           this.func1(); // Fails - this refers to the $.post request
       }, 'json');
   }
};

リクエストthisではなく、オブジェクト自体への参照ポイントを作成するにはどうすればよいですか?$.post

4

3 に答える 3

3

最も簡単な方法:

var MyObject = {
   func1 : function() {
       // Does something
   },
   func2 : function() {
       var self = this;        //self = MyObject-object
       // Send an AJAX request out
       $.post('', $('form').serialize(), function(response) {
           // Call the first function
           self.func1(); // #### NEW ####
       }, 'json');
   }
};
于 2013-07-29T12:22:12.640 に答える
0

ajax コンテキスト オプションを使用します。

$.ajax({
  context:this,
  type: "POST",
  url: url,
  data: data,
  success: this.func1,
  dataType: dataType
});
于 2013-07-29T12:22:56.510 に答える