使用 Codeigniter 和 jQuery 表单插件上传 Ajax 文件

标签 ajax codeigniter file-upload

我想将 jQuery 表单插件与 Codeigniter 结合使用。当我尝试上传时,页面被重定向(因此ajax不起作用)并且没有上传任何内容。

表单所在位置的 View 如下所示:

<form id="upload_form" action="upload/do_upload" method="post" enctype="multipart/form-data">
   <input type="file" name="myfile"><br>
   <input type="submit" value="Upload File to Server">
</form>

<div class="progress">
        <div class="bar"></div >
        <div class="percent">0%</div >
</div>
<div id="status"></div>

<script>
(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('#upload_form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
  complete: function(xhr) {
    status.html(xhr.responseText);
  }
}); 

})();   
</script>    
<script type="text/javascript" src="http://localhost/editor/assets/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://localhost/editor/assets/js/jquery.form.js"></script>
</body>

上传的 Controller 取自 Codeigniter 手册:

<?php

class Upload extends CI_Controller {

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

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

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());

            //$this->load->view('upload_form', $error);   TODO echo error 
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());

            //$this->load->view('upload_success', $data);  TODO echo succes
        }
    }
}
?>

我确定我在某个地方犯了一个小错误,有人能看出我哪里出了问题吗?提前致谢!

最佳答案

看起来您忘记在 DOM 准备就绪时初始化表单。

$(document).ready(function() { 
        // bind 'myForm' and provide a simple callback function 
        $('#upload_form').ajaxForm(function() { 
            //rest of your code from the post
        }); 
    }); 

关于使用 Codeigniter 和 jQuery 表单插件上传 Ajax 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15443937/

相关文章:

javascript - 通过 jQuery AJAX for MYSQL 传递多维数组

php - 长轮询超出最大执行时间

javascript - Chrome 开发者工具未捕获 AJAX 请求

php - 在同一时刻将 id(自动递增)插入到其他表中

php - 未声明 HTML 文档的字符编码 codeigniter

php - where 和 or_where codeigniter ajax 数据表搜索不适用于(2 where)

java - 当我使用 html 表单和 php 上传文件时,我还可以将该文件传递给 java 小程序吗?

Javascript,禁用按钮后,需要使其再次可用。 JS 不工作

javascript - 如何使用django + react有效处理大文件上传?

javascript - iframe 的跨域问题