2012-04-06 116 views
1

我有一個頁面上的選擇列表,我遍歷所有選擇列表。這些值是「默認」,「無故缺席」和「遲到諒解」。默認基本上是「選擇...」。我不想將它傳遞給服務器,或者因爲沒有意義而對它進行任何處理。爲什麼我會在這個數組中獲得NULL值?

這是我的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,在jQuery中發現了默認的次數爲NULL。當然,我應該只能得到沒有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);   
     }); 
    } 

我不明白爲什麼我得到空值的時候,它甚至不if語句進入在jQuery中。

回答

1

您的問題是在這條線的位置:

students[k] = 

相反,你應該使用.push()

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

k值是attendSelect正在處理的索引。在創建學生數組時,您正在分配這些索引鍵,而不是僅創建一個新數組。 Javascript正在用NULL值填充缺失的索引。

+0

已排序。謝謝 :) – 2012-04-06 20:35:12

1

JSON中的數組不能跳過索引。

您可以通過使用array_filter(不要傳遞任何東西作爲第二個參數)來篩選出null值。

相關問題