那里';在Javascript/Jquery中,它类似于require once
我用Javascript创建了一个类,但我希望在我的那里';在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;
构造函数中创建一个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;
}
});
}
检查此
在匿名函数中引用的内容。