JavaScript类财产Ajax调用成功,函数没有设置 [英] javascript class property not set in success function of ajax call

查看:106
本文介绍了JavaScript类财产Ajax调用成功,函数没有设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉的重复,但我可以找到其他职位的任何解决方案。

我试图填补使用Ajax调用webservice的JavaScript对象。我不明白这个逻辑,为什么我的对象调用后未设置。我写了这个小例子来解释我的问题:

code:

 函数CELLULE(){
    this.test = 0;
    this.textfunction();
}Cellule.prototype.textfunction =功能(){
    this.test = 1;
    $阿贾克斯({
        键入:GET,
        网址:BASEURL / cellules
        数据:,
        成功:函数(MSG){
            的console.log(成功);
            this.test = 2;
            的console.log(小细胞);
        }
    });
};VAR小细胞=新CELLULE();

控制台出来:

 成功
CELLULE {测试:1}


解决方案

  

这个不引用小细胞


使用 .bi​​nd( ) 背景 AJAX 设置参数

绑定()方法创建一个新的函数,调用它时,有该关键字设置为提供的值

或指定背景:该将在成功处理程序使用小细胞上下文

试试这个:

\r
\r

函数CELLULE(){\r
  this.test = 0;\r
  this.textfunction();\r
}\r
\r
Cellule.prototype.textfunction =功能(){\r
  this.test = 1;\r
  $阿贾克斯({\r
    键入:GET,\r
    网址:../slimrest/andon/cellules\r
    数据:,\r
    成功:函数(MSG){\r
      的console.log(成功);\r
      this.test = 2;\r
      的console.log(小细胞);\r
    } .bind(本)\r
  });\r
};\r
\r
VAR小细胞=新CELLULE();

\r

\r
\r

Sorry for the duplication but I can find any solution in the others posts.

I'm trying to fill a javascript object using a ajax call to a webservice. I don't understand the logic of this and why my object in not set after the call. I wrote this little example to explain my problem :

Code :

function Cellule(){
    this.test = 0;
    this.textfunction();
}

Cellule.prototype.textfunction = function(){
    this.test = 1;
    $.ajax({
        type: "GET",
        url: "BASEURL/cellules", 
        data: "",
        success: function(msg){
            console.log("success");
            this.test = 2;
            console.log(cellule);
        }
    });
};

var cellule = new Cellule();

Console out :

success
Cellule {test: 1}

解决方案

this does not refer to cellule

Use .bind() or context in argument of ajax settings

The bind() method creates a new function that, when called, has its this keyword set to the provided value

Or specifying context: this will use context of cellule in success handler.

Try this:

function Cellule() {
  this.test = 0;
  this.textfunction();
}

Cellule.prototype.textfunction = function() {
  this.test = 1;
  $.ajax({
    type: "GET",
    url: "../slimrest/andon/cellules",
    data: "",
    success: function(msg) {
      console.log("success");
      this.test = 2;
      console.log(cellule);
    }.bind(this)
  });
};

var cellule = new Cellule();

这篇关于JavaScript类财产Ajax调用成功,函数没有设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆