让Django的views.py返回并执行javascript

发布于 2024-11-27 23:41:03 字数 978 浏览 2 评论 0原文

所以我正在使用 django 和文件上传,我需要一个 javascript 函数在文件上传后执行。 我的views.py 中有一个文件上传处理程序,如下所示:

def upload_file(request):   
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():        
        for f in request.FILES.getlist('fileAttachments'):     
            handle_uploaded_file(f)
        return HttpJavascriptResponse('parent.Response_OK();')
    else:
        return HttpResponse("Failed to upload attachment.")

我从 http:// 找到了一个 django 片段/djangosnippets.org/snippets/341/ 我将 HttpJavascriptResponse 类放入我的views.py 代码中。它看起来如下:

class HttpJavascriptResponse(HttpResponse):
    def __init__(self,content):
       HttpResponse.__init__(self,content,mimetype="text/javascript")

但是,当我上传文件时,浏览器简单地呈现“parent.Response_OK();”在屏幕上而不是实际执行 javascript。 Chrome 给我警告:“资源解释为文档,但使用 MIME 类型文本/javascript 传输”

是否有办法让views.py 执行脚本?

So I'm working with django and file uploads and I need a javascript function to execute after the file has been uploaded.
I have a file upload handler in my views.py which looks like this:

def upload_file(request):   
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():        
        for f in request.FILES.getlist('fileAttachments'):     
            handle_uploaded_file(f)
        return HttpJavascriptResponse('parent.Response_OK();')
    else:
        return HttpResponse("Failed to upload attachment.")

And I found a django snippet from http://djangosnippets.org/snippets/341/ and I put the HttpJavascriptResponse class in my views.py code. It looks as follows:

class HttpJavascriptResponse(HttpResponse):
    def __init__(self,content):
       HttpResponse.__init__(self,content,mimetype="text/javascript")

However, when I upload a file the browser simple renders "parent.Response_OK();" on the screen instead of actually executing the javascript. And Chrome gives me the warning: "Resource interpreted as Document but transferred with MIME type text/javascript"

Is there anyway to get views.py to execute the script?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清风无影 2024-12-04 23:41:03

更好的方法是将 mime 传递给 HttpResponse 对象。

请参阅文档:https://docs。 djangoproject.com/en/3.2/ref/request-response/#django.http.HttpRequest.content_type

    return HttpResponse("parent.Response_OK()", content_type="application/x-javascript")

注意 - 某些早期版本的 Django 使用 mimetype 而不是 content_type

    return HttpResponse("parent.Response_OK()", mimetype="application/x-javascript")

A better way is to pass the mime to the HttpResponse Object.

See documentation: https://docs.djangoproject.com/en/3.2/ref/request-response/#django.http.HttpRequest.content_type.

    return HttpResponse("parent.Response_OK()", content_type="application/x-javascript")

Note - Some previous versions of Django used mimetype instead of content_type:

    return HttpResponse("parent.Response_OK()", mimetype="application/x-javascript")
儭儭莪哋寶赑 2024-12-04 23:41:03

我相信这会起作用。

return HttpResponse("<script>parent.Response_OK();</script>")

但是,您可能会考虑在这种情况下返回成功 (200) 状态代码,然后将父级中的一些 javascript 附加到该子级的加载事件,并根据返回状态代码进行分支。这样您就可以将视图渲染代码和视图行为代码分开。

I believe this will work.

return HttpResponse("<script>parent.Response_OK();</script>")

However, you might think about returning a success (200) status code in this case, and then having some javascript in parent attach to the load event of this child, and branch based on return status code. That way you have a separation of view rendering code and view behavior code.

岁吢 2024-12-04 23:41:03

我最终在这里寻找一种使用 django 提供动态 js 文件的方法。

这是我的解决方案:

return render(request, 'myscript.js', {'foo':'bar'},
                        content_type="application/x-javascript")

I ended up here looking for a way to serve a dynamic js file using django.

Here is my solution :

return render(request, 'myscript.js', {'foo':'bar'},
                        content_type="application/x-javascript")
清风不识月 2024-12-04 23:41:03

Chase 的解决方案对我有用,尽管我需要执行的 JavaScript 数量多于我想要放入 python 字符串的数量:

from django.http import HttpResponse
from django.contrib.staticfiles.templatetags import staticfiles

...
    return HttpResponse("<script src='{src}'></script>".format(
        src = staticfiles.static('/path/to/something.js')))

Chase's solution worked for me, though I need to execute more javascript than I care to put in a python string:

from django.http import HttpResponse
from django.contrib.staticfiles.templatetags import staticfiles

...
    return HttpResponse("<script src='{src}'></script>".format(
        src = staticfiles.static('/path/to/something.js')))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文