登录

javascript - 怎样在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方法中,正确引用一个原型的方法呢?

# JavaScript
ringa_leeringa_lee2185 天前445 次浏览

全部回复(2) 我要回复

  • 伊谢尔伦

    伊谢尔伦2017-04-10 14:29:31

    找到方法了,谢谢关注!

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

    回复
    0
  • 黄舟

    黄舟2017-04-10 14:29:31

    ajaxForm.prototype.send=function(){
    $.ajax({
    url:this.opts.url,//无错
    before:this.before,//引用ajaxForm.before方法
    success:this.success.bind(this),//执行到这里错误,success内部this方法出错了
    type:'post',
    data:this.formdata
    })
    }

    bind : https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    回复
    0
  • 取消回复发送