codeigniter上传,无需重定向到成功页面

时间:2016-10-05 03:44:15

标签: javascript php ajax twitter-bootstrap codeigniter

如何在不使用Ajax重定向到成功页面的情况下在codeigniter中上传图像。  每次我点击保存它会显示一个  您没有选择要上传的文件。

这是我的观点:

<script type="text/javascript">
$(document).ready(function() {
   jQuery("input[name='upload']").click(function(){
    $.ajax({
    url : "<?php echo site_url('Upload/do_upload')?>",
    type: "POST",
    data: $('#form').serialize(),
    dataType: "JSON",
    success: function(data)
    {
        if(data.status) //if success close modal and reload ajax table
        {
            swal("Success!", "Uploaded!", "success");
        }
        else
        {
            for (var i = 0; i < data.inputerror.length; i++) 
            {
     $('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
     $('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
            }
        }

    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        alert('Error adding / update data');
    }
});

});
 });
 </script>
  </head> 
  <body>

  <?php echo $error;?>

  <?php echo form_open_multipart('upload/do_upload'); ?>
  <input type="file" name="userfile" id="uf" size="20" />
  <span class="help-block"></span>
  <br /><br />

  <input type="button" name="upload"  value="upload" />

  </form>

  </body>
  </html>

这是我的控制器:

<?php

class Upload extends CI_Controller {

    public function __construct()
    {
            parent::__construct();
            $this->load->helper(array('form', 'url'));
    }

    public function index()
    {
            $this->load->view('pages/header');
            $this->load->view('pages/registeredlist/upload', array('error' => ' ' ));
            $this->load->view('pages/footer');
    }

    public function do_upload()
    {
            $config['upload_path']          = './uploads/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 100;
            $config['max_width']            = 1024;
            $config['max_height']           = 768;

            $this->load->library('upload', $config);
            $data = array();
            $data['error_string'] = array();
            $data['inputerror'] = array();
            $data['status'] = TRUE;

            if ( ! $this->upload->do_upload('userfile'))
                {
                    //$error = array('error' => $this->upload->display_errors());
                    $data['inputerror'][] = 'userfile';
                    $data['error_string'][] = $this->upload->display_errors();
                    $data['status'] = FALSE;
                }
            if($data['status'] === FALSE)
            {
                echo json_encode($data);
                exit();
            }
    }
}
?>

感谢。

0 个答案:

没有答案