Php 为什么我在这个数组中得到空值?
我在一个页面上有选择列表,我正在遍历所有选择列表。这些值是“默认”、“免责缺席”和“免责迟到”。默认值基本上是“选择…”。我不想把它传递给服务器,也不想用它做任何处理,因为它毫无意义 这是我的jQuery:Php 为什么我在这个数组中得到空值?,php,jquery,arrays,Php,Jquery,Arrays,我在一个页面上有选择列表,我正在遍历所有选择列表。这些值是“默认”、“免责缺席”和“免责迟到”。默认值基本上是“选择…”。我不想把它传递给服务器,也不想用它做任何处理,因为它毫无意义 这是我的jQuery: attendSelect.each(function(k, v) { attendance = $(this).val(); if(attendance != "default") { conso
attendSelect.each(function(k, v)
{
attendance = $(this).val();
if(attendance != "default")
{
console.log(attendance == "default");
students[k] =
{
lesson : $(this).attr('id'),
student_id : $(this).attr('name'),
attendance : attendance
};
}
});
这是有效的,因为每次我测试它时,它都会打印正确数量的false,在本例中为3次。然而,问题出在服务器端(我想是吧?)。当我打印变量时,我得到NULL,NULL表示在jQuery中找到默认值的次数。当然,我应该只得到一个大小为3且没有空值的数组
这是用PHP打印的内容:
$students = json_decode($_POST['students'], true);
var_dump($students);
array(12) {
[0]=>
NULL
[1]=>
NULL
[2]=>
NULL
[3]=>
array(3) {
["lesson"]=>
string(9) "lesson[7]"
["student_id"]=>
string(12) "student[241]"
["attendance"]=>
string(14) "Excused Absent"
}
[4]=>
array(3) {
["lesson"]=>
string(9) "lesson[7]"
["student_id"]=>
string(12) "student[270]"
["attendance"]=>
string(12) "Excused Late"
}
[5]=>
NULL
[6]=>
NULL
[7]=>
NULL
[8]=>
NULL
[9]=>
NULL
[10]=>
NULL
[11]=>
array(3) {
["lesson"]=>
string(9) "lesson[9]"
["student_id"]=>
string(12) "student[317]"
["attendance"]=>
string(14) "Excused Absent"
}
}
这是我的AJAX:
students = JSON.stringify(students)
if(attendSelect.length)//protect against submitting on past lessons
{
$.post('', { students : students, cid: cid }, function(response)
{
console.log(response);
});
}
我不明白为什么在jQuery中它甚至没有输入if语句时会得到null 您的问题在这一行:
students[k] =
相反,您应该使用.push()
您的
k
值是您正在处理的attendSelect
的索引。创建students数组时,将分配这些索引键,而不仅仅是创建一个新数组。Javascript正在用空值“填充”缺少的索引。JSON中的数组不能跳过索引
您可以使用过滤掉null
值(不要将任何内容作为第二个参数传递)
students.push(
{
lesson : $(this).attr('id'),
student_id : $(this).attr('name'),
attendance : attendance
});