使用jQuery和ajax无法正常上传文件

时间:2014-05-31 12:28:22

标签: php jquery ajax

文件上传在我的程序中运行良好,但仅在刷新页面后才能正常运行。

的Javascript

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="<?php echo base_url()?>Assets/Scripts/ajaxfileupload.js"></script>
<script type="text/javascript">
    function ajaxFileUpload(){
    $("#loading")
    .ajaxStart(function(){  
        $(this).show();
    })
    .ajaxComplete(function(){
        $(this).hide();
    });
    $.ajaxFileUpload
        (
            {
                url:'<?php echo site_url()?>/welcome/doupload',
                secureuri:false,
                fileElementId:'fileToUpload',
                dataType: 'json',
                success: function (data, status){
                    if(typeof(data.error) != 'undefined'){
                        if(data.error != ''){
                            $("#info").html(data.error);
                        } else {
                            $("#info").html(data.msg);
                        }
                    }
                },
                error: function (data, status, e){
                    $("#info").html(e);
                }
            }
        )
        return false;
    }
</script>

HTML

<form name="form" action="" method="POST" enctype="multipart/form-data">
    <input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input">
    <button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>  
</form>

控制器

public function doupload() {
    $error = "";
    $msg = "";
    $config['upload_path'] = './Assets/';
    $config['allowed_types'] = 'doc|xls|ppt|pdf|rar|jpg';
    $config['max_size'] = '1000';
    $this->load->library('upload', $config);
    $this->upload->display_errors('','');
    if ( ! $this->upload->do_upload("fileToUpload")) {
        $error = $this->upload->display_errors();
    } else {
        $msg = "Success";
    }
    echo "{";
    echo "error: '" . $error . "',n";
    echo "msg: '" . $msg . "'n";
    echo "}";
}

1 个答案:

答案 0 :(得分:2)

我的猜测是,在表单标记中,按钮默认为“提交”类型。

尝试将类型设置为“按钮”:

<button type="button" class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>