【问题标题】:There's something like require once in Javascript/Jquery [duplicate]在 Javascript/Jquery 中有类似 require once 的东西 [重复]
【发布时间】:2017-05-01 02:49:02
【问题描述】:

我在 Javascript 中创建了一个类,但我希望在我的 constructor 中创建一个 Ajax 请求,并且返回到我的对象属性,但它不起作用。我哪里错了?

class pergunta {
      constructor(perguntas = [], respostas = [], desafios = [], valor = 100, posicao = 0){
        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;

             }
           });

}

    }
    const perguntas = new pergunta();
    console.log(perguntas);

【问题讨论】:

  • 检查this 在你的匿名函数中指的是什么。

标签: javascript json ajax rest oop


【解决方案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;

             }
           });

}

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2017-01-07
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多