获取Django views.py以返回并执行javascript [英] Get Django views.py to return and execute javascript

查看:334
本文介绍了获取Django views.py以返回并执行javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用Django和文件上传功能,并且在文件上传后需要执行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.")

我从 http://djangosnippets.org/snippets/341/ ,然后将HttpJavascriptResponse类放入我的views.py代码中。它看起来如下所示:

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")

但是,当我上传浏览器简单呈现的文件 parent.Response_OK();在屏幕上,而不是实际执行javascript。 Chrome向我发出警告:资源被解释为文档,但以MIME类型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"

总有没有要获取views.py来执行脚本的信息? / p>

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

推荐答案

我相信这会起作用。

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

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

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.

这篇关于获取Django views.py以返回并执行javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆