javascript - 怎样在jquery.ajax中执行当前函数的其他方法?
ringa_lee
ringa_lee 2017-04-10 14:27:31
0
2
630
//简单的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方法中,正确引用一个原型的方法呢?

ringa_lee
ringa_lee

ringa_lee

reply all (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); } });
    黄舟

    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

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!