Get Django views.py to return and execute javascript

女生的网名这么多〃 提交于 2019-12-03 13:42:05

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.

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

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

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

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!