2017-05-01 14 views
-1

私はJavaScriptを使ってクラスを作成しましたが、constructorでAjaxリクエストを作成し、オブジェクト属性に戻りますが動作しません。どこが間違っている?Javascript/Jqueryで一度だけ必要なものがあります

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); 
+0

チェック'これはあなたの無名関数の中で何を意味しますか? – zerkms

答えて

-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; 

      } 
      }); 

} 
関連する問題