简体   繁体   English

在 codeigniter 中解析从 ajax 到 controller 的数组多维?

[英]Parsing array multidimension from ajax to controller in codeigniter?

I have a dynamic table and i want to send in controller by ajax.我有一个动态表,我想通过 ajax 发送 controller。 I have code ajax like this:我有这样的代码 ajax :

$(".save").click(function(e){
    var items = new Array();
    $("#list-item tr.item").each(function () {
        $this = $(this)
        var ref_item_id = $this.find("#ref_item_id").val();
        var ref_pic_id = $this.find("#ref_pic_id").val();
        var price= $this.find("#price").val();
        var qty= $this.find("#qty").val();
        items.push({ ref_item_id : ref_item_id, ref_pic_id : ref_pic_id, price: price, qty : qty});
    });

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: '<?php echo base_url("transac/save")?>',
        dataType: "json",
        data: JSON.stringify({'items': items }),
        success: function (data) {              
            var obj = $.parseJSON(data);
            alert(obj.lenth);
        },
        error: function (result) { alert(result); }
    });
})

now, how get data in controller and save in table database.现在,如何获取 controller 中的数据并保存在表数据库中。 My Controller like this:我的 Controller 像这样:

public function penjualan_save(){
    $items = $this->input->post("items");
    // next code ???
}

I hope you can help me.我希望你能帮助我。 Thanks谢谢

first thing, your don't need JSON.stringify({'items': items }), just use:首先,您不需要 JSON.stringify({'items': items }),只需使用:

data: {'items': items },

and in your controller , just create a model and pass your post data into it, for example:在您的 controller中,只需创建一个 model 并将您的帖子数据传递给它,例如:

public function penjualan_save(){
    $items = $this->input->post("items");
    $this->load->model('model_name');
    $this->model_name->insert($items);
}

then you need to define a function for your model , like this:那么您需要为您的 model定义一个 function ,如下所示:

public function insert($data)
{
    // if you didn't call database library in autoload.php
    $this->load->database();
    $this->db->insert_batch('mytable', $data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM