【问题标题】:Can't get XMLHttpRequest response with async:true无法通过 async:true 获得 XMLHttpRequest 响应
【发布时间】:2019-04-27 11:24:09
【问题描述】:

在富文本编辑器中,我想将本地图像上传到服务器媒体文件夹。为此,我做了一个 XMLHttpRequest。带有可下载文件的请求被发送到服务器,然后服务器上的一个函数保存文件并返回其 url。返回的 url 应显示在文本编辑器对话框中。起初我尝试了这段代码,使用 async:false 参数一切正常。在对话框中出现了文件的相对 url,我可以将它加载到视图页面上。下图为图片上传成功。

file_picker_callback: function(cb, value, meta) {
        if (meta.filetype == 'file') {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'MIME_type');

            input.onchange = function () {
                var file = this.files[0];
                var reader = new FileReader();

                // FormData
                var fd = new FormData();
                var files = file;
                fd.append("file",files);
                var location = "";

                // AJAX
                jQuery.ajax({
                    url: "/fileupload/file/",
                    type: "POST",
                    data: fd,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    async: false,
                    success: function(response){
                       location = response.fileurl;
                    }
                });

                reader.onload = function(){
                //call the callback and populate the Title field with the file name
                   cb(location, { download : files.name });
                };
                reader.readAsDataURL(files);
            };
            input.click();
        }
    },

但是,在控制台中,我收到“主线程上的同步 XMLHttpRequest 由于其不利影响而被弃用”消息。 然后我更改了 async:true 并且代码停止工作。文件仍上传到服务器,但 url 未显示在对话框中。我认为 FileReader 没有及时得到服务器响应。如何让 FileReader 等待 XMLHttpRequest 结束?下面是我在 Python 上的处理程序:

@require_POST
@csrf_exempt
def file_upload(request):
    data = UploadFile.objects.create(file=request.FILES['file'], related_post_id=1,)
    return JsonResponse({'fileurl': data.file.url})

【问题讨论】:

    标签: javascript ajax django python-3.x


    【解决方案1】:

    您可以在 AJAX 调用 success 函数中移动读取文件的代码。像这样的:

    jQuery.ajax({
        url: "/fileupload/file/",
        type: "POST",
        data: fd,
        dataType: 'json',
        contentType: false,
        processData: false,
        success: function(response){
            var location = response.fileurl;
            reader.onload = function(){
                //call the callback and populate the Title field with the file name
                cb(location, { download : files.name });
            };
            reader.readAsDataURL(files);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      相关资源
      最近更新 更多