繁体   English   中英

jQuery $ .ajax获取响应与将此对象嵌套传递给成功回调函数冲突

[英]Jquery $.ajax Get response conflicting with nested passing of 'this' object to 'success' callback function

我试图做一个jQuery $.ajax Get类的方法内。 Get请求提供的数据将在成功使用时在回调函数中使用,并且该类也需要在同一回调中进行修改。 所以,我不得不.apply回调在this标识的原始类的,因为否则,回调里面, this是越来越局部更换。 但是在this应用回调时, Get返回的数据为undefined 我如何解决此问题。 任何帮助表示赞赏。

var tableblock = function(tablename){
     this.tablename = tablename;
     this.numusers = 0;
     this.userpool = new Array();

     this.addme = function(){
        bodyContent = $.ajax({
            type: "GET",
            url: "controllers/bestpals.php",
            data: "addpal=1&palname="+userid+"&nocache="+Math.floor((Math.random()*100)+1),
            error: function(xhr, statusText){alert('could not add pal. refresh page.');},
            success: function(msg){
                alert(msg); // this will give undefined when .apply(this) 
                myid = msg;
                syncpals(this,true);
            }.apply(this) // using this alert(msg) above gives undefined 
        });
     };
 }

您可以在ajax配置中提供context参数。 所有的Ajax回调将在上下文中调用(即this回调中会参考你传递的价值context$.ajax()调用):

SomeClass.prototype.methodName = function() {
    $.ajax({
        ....
        context: this    // callbacks will be called with the same context that methodName() is running in
        ....
    });
}

您需要.bind(this) ,而不是.apply(this) bind更改函数的this指针,而apply实际上在新上下文中运行该函数。

我觉得你的意思bindapply bind创建一个新函数,在设置this函数时调用包装的函数; applyaddme()运行后立即调用该函数。

但是bind是ECMAScript第五版的功能,因此您需要执行以下一项操作:

  1. 适用于较旧浏览器的polyfill bind
  2. 使用jQuery等效proxy ;
  3. 使用context参数ajax ,它设置this明确;
  4. 记住var that= this; addme并在内部函数中使用附带的that引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM