如何使用ajax将数据从视图传递到控制器?

时间:2015-03-03 07:14:58

标签: javascript php ajax

从我的观点来看,我可以在用户点击上传时上传文件,然后文件应该调用ajax并将该文件名传递给我的控制器。然后控制器将执行其步骤。

view.php:

 <form enctype='multipart/form-data' method="post" class="form-horizontal" id="myform">
                                <div class="control-group">
                                    <label class="control-label" for="fileInput">Select file</label>
                                    <div class="controls">
                                        <input class="input-file uniform_on" id="file" name="file" type="file">
                                        <input type="submit" class="blue btn" value="Add" id="submitbutton">

                                    </div>
                                    <br>
                                    <div class="controls">
                                        <a href="">Or add single user</a>
                                    </div>
                                </div>          


                            </form>

脚本:

 <script>   
                $(document).ready(function() {
                    $("#submitbutton").click(function(e) {

                        $.ajax({
                            url: '/admin_user_controller/addtodb/',
                            type: 'POST',
                            data: $("#myform").serialize(),
                            success: function() {
                                alert("success");
                                $('#file').val('');

                            },
                            error: function() {
                                alert("Fail");
                            }
                        });
                        e.preventDefault(); // could also use: return false;
                    });
                });
            </script>

控制器:

 public function addtodb() {

        $name=$this->input->post('file');
        echo $name;
        $uploaddir = 'uploads/';
        $uploadfile = $uploaddir . basename($_FILES["file"]["name"]);
        echo $uploadfile;
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $uploadfile)) {
            $handle = fopen("$uploadfile", "r");
            $no = 0;
            while (($data = fgetcsv($handle)) !== FALSE) {
                $temp[$no] = $data[0];
                $no++;
            }
            $this->load->model('admin_user_model');
            $flag = $this->admin_user_model->insertrecord($temp, $name);
            echo $flag;
            if ($flag) {
                $this->load->view('admin_user_view');
            }
            fclose($handle);
        }
        echo "done";
    }

0 个答案:

没有答案