gpt4 book ai didi

javascript - Mootools - 如何修复初始化和 ajax 请求内的变量范围

转载 作者:行者123 更新时间:2023-12-02 20:12:53 27 4
gpt4 key购买 nike

我无法让 for 循环读取请求之外的 maxSlots 变量。我不知道如何或在哪里声明变量以使其对于每个类都是本地的,但对于洞类来说是全局的。

//INITIALIZATION
initialize: function(){

maxSlots = 0;
var myRequest = new Request({

url: 'getInventory.php',
method: 'post',
onSuccess: function(responseText){

maxSlots = responseText;
console.log(maxSlots);
},

onSFailure: function(){
alert('noo');
}

});
myRequest.send();

for (var i = 1; i <= maxSlots; i++){

var slot = new Element('div', {id: 'slot'+i, class: 'slot'});
slot.inject(invContainer);
}


}

编辑:好吧,我尝试将变量更改为选项,请求内的警报= 12,但如果我在请求后发出警报,它会说未定义...仍然是同样的问题。

//VARIABLES
options: {
id: '',
size: '',
maxSlots: '2'
},

//INITIALIZATION
initialize: function(options){

this.setOptions(options);
var myRequest = new Request({

url: 'getInventory.php',
method: 'post',
onSuccess: function(responseText){

this.maxSlots = responseText;
alert(this.maxSlots)
},

onSFailure: function(){
alert('noo');
}

});
myRequest.send();

alert(this.maxSlots)
for (var i = 1; i <= this.maxSlots; i++){

var slot = new Element('div', {id: 'slot'+i, class: 'slot'});
slot.inject(invContainer);
}

}

最佳答案

试试这个:

   initialize: function(){

this.maxSlots = 0;
var myRequest = new Request({

url: 'getInventory.php',
method: 'post',
onSuccess: function(responseText){

this.maxSlots = responseText;
console.log(this.maxSlots);
}.bind(this), // <-- always bind the scope in functions

onSFailure: function(){
alert('noo');
}

});
myRequest.send();

for (var i = 1; i <= this.maxSlots; i++){

var slot = new Element('div', {id: 'slot'+i, class: 'slot'});
slot.inject(invContainer);
}


}

您还可以将变量保存在this.options

祝你好运

关于javascript - Mootools - 如何修复初始化和 ajax 请求内的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6743559/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com