【发布时间】:2023-03-13 02:04:01
【问题描述】:
- 收听输入字段中的“Keyup”
- 将“enableSubmitButton”定义为数组
- 做一些事情
- 将数组元素添加到“enableSubmitButton”数组中
- 我正在从当前输入字段搜索父表单,然后循环所有输入字段
- 在这个循环中,我向服务器发出请求
- 在“onreadystatechange”函数中,我将另一个元素推送到“enableSubmitButton”数组中
问题是,我在“onreadystatechange”中推送的元素实际上并不在数组中。 当我使用console.log()查看数组时,元素是可见的,但如果我使用“array.length”函数,则数组元素不包括在内:-O
$('.checkEmail, .checkPwd, .checkPwdC').bind("keyup", function() {
//define enableSubmitButton as an array
var enableSubmitButton = [];
//loop each input field in the form
$(this).parents("form").find(":input").each(function(index,data){
//do some "if then else" and other stuff
...
enableSubmitButton.push(true);
...
// Now I make a request to the server with Ajax
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText == "doesntExist"){
enableSubmitButton.push(true);
}else{
enableSubmitButton.push(false);
}
}
};
//Request
xmlhttp.open("GET", "ajax.php?ajaxCase=cuna&userName="+$('#fNewAccount input.checkAvailability').val(), true);
xmlhttp.send();
});
// PROBLEM
// and here we have the problem. To debugg, i use the console.log() function as follow
var okForSubmit = true;
console.log(enableSubmitButton);
console.log("array length: "+enableSubmitButton.length);
for(var i = 0 ; i < enableSubmitButton.length ; i++){
if(enableSubmitButton[i] == false){
okForSubmit = false;
}
var newTime = Math.floor(Math.random() * (100 - 1 + 1)) + 1;
console.log(i+" - "+enableSubmitButton[i]+" - "+newTime+" - "+okForSubmit);
}
});
这是 console.log() 的输出:
(4) [true, true, true, true]
0: true
1: true
2: true
3: true
4: false
length: 5
__proto__: Array(0)
array length: 4
0 - true - 54 - true
1 - true - 19 - true
2 - true - 51 - true
3 - true - 94 - true
有什么想法吗?
【问题讨论】:
-
只是一个小问题,你能解释一下为什么你在 URL 中使用
$('#fNewAccount input.checkAvailability')提出请求吗?它不依赖于您正在迭代的input元素,因此该URL 在each循环的每次迭代中都是相同的URL。这不应该是$(this)或类似的吗? -
请注意,
onreadystatechange在您记录之前不会在此代码中运行。那是一个事件处理程序,因此它第一次可以运行是在整个事件处理程序(keyup)完成之后。 JavaScript 一次处理一个事件,没有重叠。考虑评论整个 XHR 部分进行测试,false来自其他地方。
标签: javascript arrays