通过Django将Python数据传递给JavaScript [英] Passing Python Data to JavaScript via Django

查看:131
本文介绍了通过Django将Python数据传递给JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django和Apache来提供网页。我的JavaScript代码当前包括一个数据对象,其值将根据用户从选择菜单中的选择显示在各种HTML小部件中。我想从Python字典中导出这些数据。我想我知道如何将JavaScript代码嵌入到HTML中,但是如何将数据对象嵌入到该脚本中(即时),以便脚本的功能可以使用?



换句话说,我想从Python字典创建一个JavaScript对象或数组,然后将该对象插入到JavaScript代码中,然后将该JavaScript代码插入到HTML中。



我认为这个结构(例如,嵌入在JavaScript代码中的变量的数据)是次优的,但作为一个新手,我不知道这些替代方案。我已经看到了Django序列化功能的写作,但是这些函数在我可以首先将数据存入我的JavaScript代码之前不会帮助我。



I我不建议使用jQuery这样的JavaScript库。

解决方案

往往难以编写和调试,特别是随着您的项目扩展。相反,请尝试将所有JavaScript写入单独的脚本文件,模板加载,并在模板中只包含一个JSON数据对象。这样,您可以通过像 JSLint ,将其缩小等来运行整个JavaScript应用程序,您可以使用静态HTML文件进行测试,而不会对Django应用程序造成任何依赖。使用像simplejson这样的库也可以节省您花费繁琐的序列化代码的时间。



如果您不假设您正在构建一个AJAX应用程序,这可能只是完成像这样:



在视图中:

  from django.utils import simplejson 


def view(request,...):
js_data = simplejson.dumps(my_dict)
...
render_template_to_response(my_template.html ,{my_data:js_data,...})

在模板中:

 < script type =text / javascript> 
data_from_django = {{my_data}};
widget.init(data_from_django);
< / script>

请注意,数据类型重要:如果 my_data 是一个简单的数字或来自受控源的字符串,不包含HTML,如格式化日期,不需要特殊处理。如果用户可以提供不受信任的数据,那么您需要使用 escape escapejs 过滤并确保您的JavaScript安全地处理数据,以避免跨站点脚本攻击。



就日期而言,您可能还想考虑如何传递日期。几乎总是发现最简单的方法是将它们作为Unix时间戳传递:



在Django中:

  time_t = time.mktime(my_date.timetuple())

在JavaScript中假设您已经做了类似于 time_t = {{time_t}} 的上述代码片段的结果:

  my_date = new Date(); 
my_date.setTime(time_t * 1000);

最后,请注意UTC - 您将希望Python和Django日期函数交换数据以UTC为单位,以避免用户本地时间的尴尬变化。



编辑:请注意,javascript中的setTime为毫秒,而time.mktime的输出为秒。这就是为什么我们需要乘以1000


I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?

Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.

I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.

I'm not (yet) using a JavaScript library like jQuery.

解决方案

I recommend against putting much JavaScript in your Django templates - it tends to be hard to write and debug, particularly as your project expands. Instead, try writing all of your JavaScript in a separate script file which your template loads and simply including just a JSON data object in the template. This allows you to do things like run your entire JavaScript app through something like JSLint, minify it, etc. and you can test it with a static HTML file without any dependencies on your Django app. Using a library like simplejson also saves you the time spent writing tedious serialization code.

If you aren't assuming that you're building an AJAX app this might simply be done like this:

In the view:

from django.utils import simplejson


def view(request, …):
    js_data = simplejson.dumps(my_dict)
    …
    render_template_to_response("my_template.html", {"my_data": js_data, …})

In the template:

<script type="text/javascript">
    data_from_django = {{ my_data }};
    widget.init(data_from_django);
</script>

Note that the type of data matters: if my_data is a simple number or a string from a controlled source which doesn't contain HTML, such as a formatted date, no special handling is required. If it's possible to have untrusted data provided by a user you will need to sanitize it using something like the escape or escapejs filters and ensure that your JavaScript handles the data safely to avoid cross-site scripting attacks.

As far as dates go, you might also want to think about how you pass dates around. I've almost always found it easiest to pass them as Unix timestamps:

In Django:

time_t = time.mktime(my_date.timetuple())

In JavaScript, assuming you've done something like time_t = {{ time_t }} with the results of the snippet above:

my_date = new Date();
my_date.setTime(time_t*1000);

Finally, pay attention to UTC - you'll want to have the Python and Django date functions exchange data in UTC to avoid embarrassing shifts from the user's local time.

EDIT : Note that the setTime in javascript is in millisecond whereas the output of time.mktime is seconds. That's why we need to multiply by 1000

这篇关于通过Django将Python数据传递给JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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