在Javascript / Jquery中有一次需要的东西

时间:2017-05-01 02:49:02

标签: javascript json ajax rest oop

我已经在Javascript中创建了一个类,但我想在我的 for (var key in family_background) { family_background[key] = null; } 中创建一个Ajax请求,并且返回到我的对象属性,但它不起作用。我哪里错了?

constructor

1 个答案:

答案 0 :(得分:-1)

当您使用jQuery的AJAX函数时,回调中this的值是对请求对象的引用。如果要从父作用域访问this的值,请使用.bind

    jQuery.ajax({
       url: '../php/consulta.php' + location.search,
       type: "GET",
       dataType: 'json',
       success: function(pergunta, desafio){
           this.perguntas = pergunta.pergunta;
           this.respostas = pergunta.resposta;
           this.desafios = desafio.descricao;

         }.bind(this)
       });

如果您需要支持不允许.bind的浏览器,请使用额外的变量:

class pergunta {
      constructor(perguntas = [], respostas = [], desafios = [], valor = 100, posicao = 0){
        var _this = this;
        this.perguntas = perguntas;
        this.respostas = respostas;
        this.desafios = desafios;
        this.posicao = posicao;
        this.valor = valor;
        jQuery.ajax({
           url: '../php/consulta.php' + location.search,
           type: "GET",
           dataType: 'json',
           success: function(pergunta, desafio){
               _this.perguntas = pergunta.pergunta;
               _this.respostas = pergunta.resposta;
               _this.desafios = desafio.descricao;

             }
           });

}