[英]Django response setting a json as a cookie
I would like to set the value of a client side cookie from django as a javascript dictionary object. 我想将django的客户端cookie的值设置为javascript字典对象。 I know you can set a cookie value of a string like this in django:
我知道您可以在django中设置像这样的字符串的cookie值:
response = HttpResponseRedirect( reverse('app:home') )
response.set_cookie( 'cookiekey', 'value' )
return response
I can then read the cookie on the client side like this: 然后,我可以像这样在客户端读取Cookie:
Cookies.get( 'cookiekey' )
using the Cookies library ( https://github.com/js-cookie/js-cookie ) 使用Cookies库( https://github.com/js-cookie/js-cookie )
What I am unable to do is set the cookie to be a dictionary/json object: 我无法做的是将cookie设置为字典/ json对象:
I have tried this: 我已经试过了:
response.set_cookie( 'cookiekey', {'value' : 'value'} )
and 和
import json
response.set_cookie( 'cookiekey', json.dumps( {'value' : 'value'} ) )
and then tried to read the cookie back on the client side using: 然后尝试使用以下方法在客户端读取Cookie:
Cookies.getJSON( 'cookiekey' )
but this doesn't seem to give me back a javascript dictionary object (neither does Cookies.get) but instead a string: 但这似乎并没有给我带回javascript字典对象(Cookies.get也没有),而是一个字符串:
var message = Cookies.getJSON( 'cookiekey' );
alert( typeof message );
Use this in your Python script to set the cookie: 在您的Python脚本中使用它来设置cookie:
response.set_cookie("json", json.dumps({"foo":"bar"}))
And use this in your JavaScript to get the cookie, using JSON.parse
rather than Cookies.get
: 并在您的JavaScript中使用
JSON.parse
而不是Cookies.get
来获取Cookie:
JSON.parse(Cookies.get( 'json' ))
This worked for me :) 这对我有用:)
EDIT: 编辑:
Use JSON.parse(Cookies.get( 'json' ).split('\\\\').join('');
to remove all backslashes if that's an issue 使用
JSON.parse(Cookies.get( 'json' ).split('\\\\').join('');
删除所有反斜杠(如果存在问题)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.