Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
那里';在Javascript/Jquery中,它类似于require once_Javascript_Json_Ajax_Rest_Oop - Fatal编程技术网

那里';在Javascript/Jquery中,它类似于require once

那里';在Javascript/Jquery中,它类似于require once,javascript,json,ajax,rest,oop,Javascript,Json,Ajax,Rest,Oop,我用Javascript创建了一个类,但我希望在我的构造函数中创建一个Ajax请求,并且返回到我的对象属性,但它不起作用。我错在哪里 class pergunta { constructor(perguntas = [], respostas = [], desafios = [], valor = 100, posicao = 0){ this.perguntas = perguntas; this.respostas = respostas;

我用Javascript创建了一个类,但我希望在我的
构造函数中创建一个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);

使用jQuery的AJAX函数时,回调中的
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;

             }
           });

}

检查此
在匿名函数中引用的内容。