为什么我在这个数组中得到NULL值?

时间:2012-04-06 20:13:02

标签: php jquery arrays

我在页面上有选择列表,我正在遍历所有选择列表。值为“默认”,“原谅缺席”和“免责延迟”。默认基本上是“选择...”。我不想将它传递给服务器或使用它进行任何处理,因为它没有意义。

这是我的jQuery:

    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
            };
        }    
    });

这是有效的,因为每次测试时都会输出错误的正确次数,在这种情况下是3次。但问题出在服务器端(我认为?)。当我打印变量时,我得到NULL,NULL为jQuery中找到默认值的次数。当然,我应该只获得一个没有NULL的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。

2 个答案:

答案 0 :(得分:1)

你的问题在这一行:

students[k] = 

相反,您应该使用.push()

students.push(
        {
            lesson : $(this).attr('id'),
            student_id : $(this).attr('name'),
            attendance  : attendance
        });

您的k值是您正在处理的attendSelect的索引。在创建学生数组时,您将分配这些索引键而不是仅创建新数组。 Javascript使用NULL值“填充”缺少的索引。

答案 1 :(得分:1)

JSON中的数组不能跳过索引。

您可以使用array_filter过滤掉null值(不要传递任何内容作为第二个参数)。

相关问题