簡體   English   中英

CodeIgniter:將Javascript數組從View傳遞到Controller,然后存儲到數據庫

[英]CodeIgniter: Pass Javascript Array from View to Controller then store to Database

我正在嘗試將JavaScript數組發布到codeigniter中的控制器函數,然后通過AJAX將其存儲到數據庫中。 傳遞單個值時我沒有問題,這是我第一次傳遞數組。

這是代碼

//JAVASCRIPT IN THE VIEW (students variable already populated and classCode already has a value)
$.ajax({
    traditional: true,
    type: 'POST',
    url: '<?php echo base_url(); ?>index.php/ams_controller/recordAbsence', 
    data: 'classCode='+classCode+'&students='+students, 
    success: function(resp) { 
        alert("Absences Saved");
    }
});


//CONTROLLER FUNCTION
public function recordAbsence() {
    $temp=getdate(date("U"));
    $date = $temp[month] ." ". $temp[mday] ." ". $temp[year];

    $classCode = $this->input->post('classCode');
    $students = $this->input->post('students');

    $this->load->model('model_users');
    if($this->model_users->recordAbsence($classCode, $students, $date)) {
        return true;
    } else{
        return false;
    }    
}

//MODEL FUNCTION
public function recordAbsence($classCode, $students, $date) {
    foreach($students as $row) {
        $data = array(
            'stud_no' => $row,
            'date_of_absence' => $date,
            'classCode' => $classCode
        );

        $query = $this->db->insert('absence', $data);
    }
    if($query) {
        return true;
    } else {
        return false;
    }
}

數據未存儲在缺席表中。 任何幫助,將不勝感激。

像對象一樣傳遞數據:

data: {classCode: classCode, students: students},

編輯:此外,谷歌搜索下“ jquery ajax傳遞數組”下的現有問題會給你這個作為第一個鏈接。 在那里也檢查前兩個答案。

編輯:20160525171759

您可以傳遞JSON字符串化數組JSON.stringify(array)並使用json_decode($this->input->post('postKey'))

//JS

//students = ["2014-52307", "2014-26571", "2014-68959", "2014-60379", "2014-56077"];
students = JSON.stringify(students);
//check if same is needed for classCode variable since I don't know if classCode is array too
$.ajax({
    //I removed traditional property to pass an object
    type: 'POST',
    //I put URI as method argument (check if index.php is sufficient)
    url: '<?php echo base_url("index.php/ams_controller/recordAbsence"); ?>', 
    data: {classCode: classCode, students: students}, 
    success: function(resp) { 
        alert("Absences Saved");
    }
});

//PHP
$students = $this->input->post('students');
//echo $students;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM