怎样在jquery.ajax中执行当前函数的其他方法?

//简单的ajax表单提交
(function($,window,undefined){
    var ajaxForm=function(opts){
       var def={successLabel:'发送成功',url:'/user/check',dataType:'html'}
       this.form=$('#'+formid)||$('form');
       this.opts=$.extend({},def,opts);
       this.formdata=this.form.serialize();
    }
    //发送前执行
    ajaxForm.prototype.before=function(){
        this.submitButton=$form.find(':submit');
        this.submitButton.val('提交中...');
    }
    //请求成功回执函数
    ajaxForm.prototype.success=function(data){
        $('#message')=this.opts.successLabel;
    }
    //
    ajaxForm.prototype.send=function(){
        $.ajax({
            url:this.opts.url,//无错
            before:this.before,//引用ajaxForm.before方法
            success:this.success,//执行到这里错误,success内部this方法出错了
            type:'post',
            data:this.formdata
        })
    }

    window.ajaxForm=ajaxForm;
})(jQuery,window)

//实例
new ajaxForm().send();

以上执行,会提示this.opts.successLabel未定义,我知道当ajax引用this.success的时候,success内部this已经指向当前ajax对象了,请问各位老师,如何在ajax方法中,正确引用一个原型的方法呢?

阅读 8.5k
2 个回答

找到方法了,谢谢关注!

var _this = this;
$.ajax({
    type: this.opts.method,
    url: this.opts.url,
    dataType: this.opts.data_type,
    data: postdata,
    success: function() {
        _this.success.apply(_this, arguments);
    },
    error: function() {
        _this.error.apply(_this, arguments);
    }
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题