Javascript Krajee Bootstrap 文件输入,捕获 AJAX 成功响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29626410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:41:13  来源:igfitidea点击:

Krajee Bootstrap File Input, catching AJAX success response

javascriptphpjqueryajaxtwitter-bootstrap

提问by oussama kamal

I'm using Krajee the Bootstrap File Input plugin to perform an upload via AJAX call.

我正在使用 Krajee Bootstrap 文件输入插件通过 AJAX 调用执行上传。

Here is the link to the Krajee plugin AJAX section: Krajee plugin AJAX

这是 Krajee 插件 AJAX 部分的链接:Krajee 插件 AJAX

The JS and PHP (codeigniter) codes I'm using are as following:

我使用的 JS 和 PHP (codeigniter) 代码如下:

JS:

JS:

<script>        
    $("#file-upload").fileinput({ 
        'allowedFileExtensions' : ['csv'],
        'maxFileSize': 5120,
        'maxFileCount': 1,
        'uploadUrl': 'dashboard/uploader',
        'elErrorContainer': '#errorBlock',
        'uploadAsync': true,
        'msgInvalidFileExtension': 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
        'uploadExtraData': {csrf_token_name: $("input[name=csrf_token_name]").val()}
    });       
</script>

PHP:

PHP:

public function uploader(){
    $config['upload_path'] = './csv_uploads/';
    $config['allowed_types'] = 'csv';
    $config['max_size'] = '5120';

    $this->upload->initialize($config);
    if (!$this->upload->do_upload("file-upload")){
        $data['error'] = 'The following error occured : '.$this->upload->display_errors().'Click on "Remove" and try again!';
        echo json_encode($data); 
    } else {
        echo json_encode("success"); 
    }            
}

Right now I get a response from PHP whatever it is an error or a success as JSON, I have went through the plugin documentation and I still can't find how to catch the AJAX response and act according to that response as we do in jQuery with the ajax success function :

现在我收到了来自 PHP 的响应,无论它是错误还是成功作为 JSON,我已经浏览了插件文档,但我仍然找不到如何像在 jQuery 中那样捕获 AJAX 响应并根据该响应采取行动使用 ajax 成功函数:

success: function (response) {
            //Deal with the server side "response" data.
         },

How can I do this?

我怎样才能做到这一点?

回答by Xavi Guirao

You can check out a demo here live demo

您可以在此处查看演示现场演示

Remember to set uploadAsync falseif you want the success event fire

如果您希望成功事件触发,请记住将uploadAsync设置为 false

Example code:

示例代码:

JS

JS

$("#input-id").fileinput({
    showRemove:false,
    showPreview: false,
    uploadUrl: "../xxxx/xxxx/XXXXXX.php", // server upload action
    uploadAsync: false,
    uploadExtraData: function() {
        return {
            bdInteli: xxxx
        };
    }
});

// CATCH RESPONSE
$('#input-id').on('filebatchuploaderror', function(event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra, 
    response = data.response, reader = data.reader;
});

$('#input-id').on('filebatchuploadsuccess', function(event, data, previewId, index) {
    var form = data.form, files = data.files, extra = data.extra, 
    response = data.response, reader = data.reader;
    alert (extra.bdInteli + " " +  response.uploaded);
});

PHP

PHP

$nombre = $_FILES["ficheroExcel"]["name"];
$bdInteli = $_POST['bdInteli'];
if (move_uploaded_file($_FILES["ficheroExcel"]["tmp_name"], $nombre) ){
    $output = array('uploaded' => 'OK' );
} else {
   $output = array('uploaded' => 'ERROR' );
}
echo json_encode($output); 

回答by Kartik V

You can read the events section on the plugin documentation pageto understand the various events provided by the plugin.

您可以阅读插件文档页面上事件部分以了解插件提供的各种事件。

It depends on how you have setup the ajax upload in the plugin. The plugin offers two ajax upload modes - synchronous and asynchronousas described in the documentation. Its asynchronous if you have uploadAsyncproperty set to true.

这取决于您如何在插件中设置 ajax 上传。该插件提供了两种ajax 上传模式 -如文档中所述的同步和异步。如果您将uploadAsync属性设置为true.

FOR AJAX SUCCESS TRAP:

对于 AJAX 成功陷阱:

FOR AJAX ERROR TRAP:

对于 AJAX 错误陷阱:

In your case you have set uploadAsyncset to true - so use the asynchronous settings/events.

在您的情况下,您已将设置uploadAsync设置为 true - 因此请使用异步设置/事件。

回答by user3033075

you can use this sample code in your test.in my test,my response data like this:

您可以在您的测试中使用此示例代码。在我的测试中,我的响应数据如下:

response data:
{
"ver":"1.0",
"ret":true,
"errmsg":null,
"errcode":0,
"data":{
    "status":"upload success",
    "originalFilename":"testFileName.txt",
    "fileName":"excelFile",
    "fileType":"text/plain",
    "fileSize":1733
}

 javascript code:
 $('#input-id').on('fileuploaded', function(event, data, previewId, index) {
    var response = data.response;
    if(response.ret ) {
        alert("upload success!"+data.response.data);
    }else{
        alert("upload failed!"+response.errmsg)
    }
    alert('File uploaded triggered'+form+"response:"+response);
    console.info(response.data);
});

回答by Ashi

refer this answer, i have done like this

参考这个答案,我已经这样做了

javascript:

javascript:

$('#input-id').on('fileuploaded', function(event, data, previewId, index) {
    var form = data.form, files = data.files, extra = data.extra,
        response = data.response, reader = data.reader;
    console.log('File uploaded successfully : ID '+ data.response.d);
});

In ASHXFile add response to the context:

ASHX文件中添加对上下文的响应:

context.Response.ContentType = "application/json";
string myId = "NewwId 1";
var wrapper = new { d = myId };
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(wrapper));

回答by Ram Pukar

<?php echo $form->field($model, 'icon_path')->widget(FileInput::classname(), [
        'options'           =>  ['accept' => 'image/*','multiple'=>false, 'id' => 'category_icon_image'],
        'pluginLoading'     =>  false,
        'pluginOptions'     =>  [
        'initialPreview'        =>  (!$model->isNewRecord) ? [
            'web/filebox/'.$model->icon_path
        ] : '',
            'initialPreviewAsData'  =>  true,
            'browseIcon'            =>  '<i class="glyphicon glyphicon-camera"></i> ',
            'showPreview'           =>  true,
            'showCaption'           =>  false,
            'showRemove'            =>  false,
            'showUpload'            =>  false,
            'showClose'             =>  false,
            'previewTemplates'      =>  'object',
            'layoutTemplates'       =>  'preview',
            'uploadUrl'             =>  'category-item/category-item/ajax-image-upload',
            'uploadAsync'           =>  false,
            'deleteUrl'             =>  Url::toRoute('category-item/delete-image?id='.$model->category_item_id)
        ],
        'pluginEvents'  =>  [
            'filebatchuploadsuccess' => 'function(event, data, previewId, index) {
                console.log(data.response)
            }',
            'filebatchselected' => "function(event,files){
                var input = $('#category_icon_image');
                input.fileinput('upload');
                $('#categoryitem-icon_path_pre').val(files[0].name);
            }",
        ],
    ])
?>