CodeIgniter:将Javascript数组从View传递给Controller然后存储到数据库

时间:2016-05-24 14:05:49

标签: javascript arrays json postgresql codeigniter

我试图将一个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;
    }
}

数据未存储在缺席表中。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

传递像object这样的数据:

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

编辑:另外,在“jquery ajax传递数组”下搜索现有问题会给你this作为第一个链接。在那里检查前两个答案。

编辑: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;