简体   繁体   English

Django的STATIC_URL和Ajax请求

[英]Django's STATIC_URL and Ajax requests

My web page makes an AJAX call to the server to dynamically select an image for display. 我的网页对服务器进行AJAX调用,以动态选择要显示的图像。 The problem I've run into is that the STATIC_URL variable evaluates to an empty string, and so the image fails to load. 我遇到的问题是STATIC_URL变量的值为空字符串,因此图像无法加载。

This is the code I'm using the render the path to the image. 这是我使用的代码渲染图像的路径。

text = "<img src=\"{{ STATIC_URL }}/images/%s\"> %s" % (ball_file, val)
t = Template(text)
tt = t.render(Context())

Any help would be much appreciated. 任何帮助将非常感激。

Why even use Template ? 为什么还要使用模板? Wouldn't this work ? 这行不行吗?

from django.conf import settings

text = u'<img src="%simages/%s"> %s' % (settings.STATIC_URL, ball_file, val)

Note that STATIC_URL should contain the trailing slash, hence %simages in this example instead of %s/images . 请注意, STATIC_URL应包含斜杠,因此在此示例中为%s/images %simages而不是%s/images

You haven't supplied any context for that template, so naturally all variables including STATIC_URL will resolve to empty. 您没有为该模板提供任何上下文,因此所有包含STATIC_URL的变量自然都会解析为空。 If you use a RequestContext, then the context processors will be run first, and therefore extra items like the static URL (and the user, and various other things) will be available. 如果使用RequestContext,则将首先运行上下文处理器,因此将提供诸如静态URL(以及用户以及各种其他内容)之类的其他项。

However I agree with jpic, you'd be better off doing this directly in Python. 但是我同意jpic,您最好直接在Python中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM