访问myclass上的方法到$ .ajax()

时间:2011-10-25 12:30:18

标签: javascript jquery class

我在Javascript类上创建了两个方法:

this.saveData = function(){
    var url_send = 'm1=1&m2=2'
    $.ajax({
        url: '/save.php',
        dataType : "text",
        data:url_send,
        type:'POST',
        success: function(data) {
            // this is does not correct
            this.showAcceptBox('error_msg_0');
        }
    });
};

this.showAcceptBox = function(msg_id){
    $('#error_box').removeClass('alert-negative');
    $('#error_box').html($('#'+msg_id).html());
    $('#error_box').show();
    setTimeout(function(){
        $('#error_box').fadeOut('slow',function(){
            $('#error_box').addClass('alert-negative');
        });
    },this.message_box_timeout);
};

如何将我的类中的调用方法更正为jQuery .ajax()

2 个答案:

答案 0 :(得分:3)

尝试在闭包中捕获this

this.saveData = function() {
    var url_send = { m1: 1, m2: 2 };
    var _self = this;
    $.ajax({
        url: '/save.php',
        dataType : 'text',
        data: url_send,
        type: 'POST',
        success: function(data) {
            _self.showAcceptBox('error_msg_0');
        }
    });
};

或使用context开关将其作为参数传递:

this.saveData = function() {
    var url_send = { m1: 1, m2: 2 };
    $.ajax({
        url: '/save.php',
        dataType : 'text',
        data: url_send,
        context: this,
        type: 'POST',
        success: function(data) {
            this.showAcceptBox('error_msg_0');
        }
    });
};

来自documentation

的引用
  

<强>上下文

     

此对象将成为所有与Ajax相关的回调的上下文。通过   默认情况下,上下文是表示ajax设置的对象   在调用中使用($ .ajaxSettings与传递给的设置合并   $阿贾克斯)。例如,如上下文所指定的那样指定DOM元素   请求的完整回调的上下文,如下所示:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    $(this).addClass("done");
  }
});

答案 1 :(得分:0)

我不知道你如何给你的msg_id:

this.showAcceptBox = function(data){
    $('#error_box').removeClass('alert-negative');
    $('#error_box').html(data);
    $('#error_box').show();
    setTimeout(function(){
        $('#error_box').fadeOut('slow',function(){
            $('#error_box').addClass('alert-negative');
        });
    },this.message_box_timeout);
};

或者你可以在你的ajax答案中找到你想要的任何东西,比如$('#msg_id',data)。一切都取决于你的回电。

相关问题