ajax上传文件后不显示响应消息

时间:2018-05-06 07:35:47

标签: php jquery ajax codeigniter jsajaxfileuploader

我是ajax的新手。我正在尝试使用codeigniter中的ajax创建文件上传器。当我上传文件文件成功上传到/ uploads文件夹但响应消息是警报或图像视图不起作用。我已经搜索了几个相同问题的答案,但无法解决。请帮我找到代码问题。

控制器:

 <?php


class AjaxImageUpload extends CI_Controller {


/**
 * Manage __construct
 *
 * @return Response
 */
public function __construct() {
    parent::__construct();
    $this->load->helper(array('form', 'url'));
}


/**
 * Manage index
 *
 * @return Response
 */
public function index() {
    $this->load->view('ajaxImageUploadForm', array('error' => '' ));
}


/**
 * Manage uploadImage
 *
 * @return Response
 */
public function uploadImage() {
    header('Content-Type: application/json');
    $config['upload_path']   = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size']      = 10240;
    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload('image')) {
        $error = array('error' => $this->upload->display_errors());
        echo json_encode($error);
    }else {
        $data = $this->upload->data();
        $success = ['success'=>$data['file_name']];
        echo json_encode($success);
    }
}
}


?>

视图文件:

<html>


<head>
    <title>Image Upload Example from Scratch</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>
</head>


<body>


    <?php echo form_open_multipart('ajax-image-upload/post');?>
    <input type="file" name="image" size="20" />
    <input type="submit" class="upload-image" value="upload" />
    </form>


    <div class="preview" style="display: none;">
       <img src="">

    </div>


</body>


</html>

ajax:

 $("body").on("click",".upload-image",function(e){
    $(this).parents("form").ajaxForm(options);
});


var options = {
    complete: function(response)
    {
        if($.isEmptyObject(response.responseJSON.error)){
            alert('Image Upload Successfully.');
            $(".preview").css("display","block");
            $(".preview").find("img").attr("src","/uploads/"+response.responseJSON.success);
        }else{
            alert('Image Upload Error.');
        }
    }
};`

1 个答案:

答案 0 :(得分:0)

if ($.isEmptyObject(response.responseJSON.success)) {
    alert('Image Upload Successfully.');
    $(".preview").css("display", "block");
    $(".preview").find("img").attr("src", "/uploads/" + response.responseJSON.success);
} else {
    alert('Image Upload Error.');
}