简体   繁体   English

将值从Django服务器发送到客户端?

[英]Send values from django server to client?

I would like to give some values to my client (to use them in javascript) from my django server. 我想从我的django服务器给我的客户端一些值(在javascript中使用它们)。

I know that I can use cookies , but the problem is that they are kept for all request whereas I need them only once when the client loads for the first time (it is not really a problem). 我知道我可以使用cookie ,但是问题是,所有请求都将保留它们,而当客户端第一次加载时,我只需要它们一次(这并不是真正的问题)。

I could also pass those values to the template to render some html tags with the "data-value-name" properties set the the values (for example <body data-name="joe" data-id="123456"> ) 我还可以将这些值传递给模板,以使用“ data-value-name”属性设置值来呈现一些html标签(例如<body data-name="joe" data-id="123456">

Both solutions work fine, but is there a better method? 两种解决方案都可以正常工作,但是有更好的方法吗?

What I usually do is to create a <script> element where I render the values directly to JavaScript objects stored in local or global variables. 我通常要做的是创建一个<script>元素,在其中将值直接呈现给存储在局部或全局变量中的JavaScript对象。

If you have a lot of values you can also consider implementing a view that returns JSON which is requested via ajax from the client. 如果您有很多值,也可以考虑实现一个返回JSON的视图,该视图是通过客户端从ajax请求的。

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

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