javascript - POST 文件上传的 django JsonResponse

标签 javascript python json django

我正在使用 django 的 fileupload 并让示例中的文档正常工作。现在,我想使用 JsonResponse 修改响应像这样:

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            # this is default as in django 1.7 docs:
            # return HttpResponseRedirect('/success/url/')
            # this is what I want to implement
            return JsonResponse({'foo': "bar"})
    else:
        form = UploadFileForm()
        return render_to_response('upload.html', {'form': form})

现在,我想要在我的模板上显示此 return JsonResponse({'foo': "bar"})。但是,我不确定如何在 JS 端获取此变量。例如,类似:

<script type='text/javascript'>
    var data = {{ foo }};
    console.log(data);
</script>

..但这不起作用 - 我不确定如何使用 django 中的 JsonResponse 对象获取 JS 中的数据。

对此的任何帮助都会很棒!

更多信息

由于我使用 dropzone.js 来处理文件上传,因此我有以下 JS 代码:

## load dropzone.js
<script type="text/javascript">
    Dropzone.options.myDropzone = {
        paramName: "file_field", // The name that will be used to transfer the file
        maxFilesize: 20, // MB
        // Prevents Dropzone from uploading dropped files immediately
        autoProcessQueue : true,
        clickable : true,

  init: function() {
    this.on("success", function(file, responseText) {
      // Handle the responseText here. For example, add the text to the preview element:
      file.previewTemplate.appendChild(document.createTextNode({{django_json}}));
    });
  }

        };

    </script>

最佳答案

您发布的 JS 片段显示了您需要处理返回的 JSON 的位置。数据作为“responseText”传递到您的成功函数:

this.on("success", function(file, responseText) {
  file.previewTemplate.appendChild(responseText);
});

但您可能希望使用 JSON.parse 将其转换为实际的 JS 对象。

关于javascript - POST 文件上传的 django JsonResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27382871/

相关文章:

python - 如何使用 Wampserver 安装 Python

python - 如何在 Airflow 中使用 s3 hook

javascript - 如何从 JSON 数组中获取特定数据?

python - 从 JSON 中寻找值(value)

json - 设计数据结构

javascript - jQuery DataTable 添加行第一位置

javascript - HTML5中属性的回退解决方案

javascript - 用户点击提交后提供反馈

javascript - Chrome 扩展程序不会运行 JS onClick

python - 我可以使用参数插入来指定 MySQL 查询的列名吗?