如何将布尔值从 javascript 传递到 python?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10693630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a boolean from javascript to python?
提问by David542
The following seems to pass a string instead of a boolean value. How would I pass a boolean?
以下似乎传递一个字符串而不是布尔值。我将如何传递布尔值?
$.post('/ajax/warning_message/', {'active': false}, function() {
return
});
def warning_message(request):
active = request.POST.get('active')
print active
return HttpResponse()
回答by óscar López
In your Python code do this:
在您的 Python 代码中执行以下操作:
active = True if request.POST.get('active') == 'true' else False
Or even simpler:
或者更简单:
active = request.POST.get('active') == 'true'
Be aware that the get()
function will always return a string, so you need to convert it according to the actual type that you need.
请注意,该get()
函数将始终返回一个字符串,因此您需要根据您需要的实际类型对其进行转换。
回答by VisioN
Assuming that you could send boolean value to the server as true/false
or 1/0
, on the server-side you can check both cases with in
:
假设您可以将布尔值作为true/false
or发送到服务器1/0
,在服务器端,您可以使用以下命令检查这两种情况in
:
def warning_message(request):
active = request.POST.get('active') in ['true', '1']
print active
return HttpResponse()
Otherwise, if you are sure that your boolean will be only true/false
use:
否则,如果您确定您的布尔值将只true/false
使用:
def warning_message(request):
active = request.POST.get('active') == 'true'
print active
return HttpResponse()
回答by ghosh
The answer by Oscar is a 1-liner and I'd like to take nothing from it but, comparing strings is not the cleanest way to do this.
Oscar 的答案是 1-liner,我什么都不想做,但是比较字符串并不是最简洁的方法。
I like to use the simplejsonlibrary. Specifically loadsparses the natural json form of JavaScript to native Python types. So this technique can be used for a wider set of cases.
我喜欢使用simplejson库。专门加载将 JavaScript 的自然 json 形式解析为原生 Python 类型。因此,该技术可用于更广泛的情况。
This will give you uniform code techniqueswhich are easier to read, understand & maintain.
这将为您提供更易于阅读、理解和维护的统一代码技术。
From the docs:
从文档:
Deserialize s (a str or unicode instance containing a JSON document) to a Python object.
将 s(包含 JSON 文档的 str 或 unicode 实例)反序列化为 Python 对象。
import simplejson as sjson
valid_python_var = sjson.loads(json_str_to_parse)
Or in the likely scenario that you are receiving it via parameter passing:
或者在您通过参数传递接收它的可能情况下:
var_to_parse = request.POST.get('name_of_url_variable') #get url param
if var_to_parse is not None: #check if param was passed, not required
parsed_var = sjson.loads(var_to_parse) # loads does the work
Note: Import libraries using common sense, if you are going to use them once there is no need for it.
注意:使用常识导入库,如果您打算使用它们,则不需要它。