1

我正在使用MySQLdbPython 读取 MySQL 记录。其中一列有点。当我将其转换为 JSON(它显示为转换前)并将其发送到浏览器时,它显示为 Python 控制台中的任何一个\\u0000\\u0001在 Python 控制台上,浏览器什么也不显示。我假设这是因为它不知道 Unicode 的字符。json.dumps\x00

有没有办法让我通过在客户端或服务器上进行操作来获取 JavascriptTrue或这些值?False

4

1 回答 1

1

在服务器端操作它很简单:

import json

def convert_to_bool(bstring):
    return True if bstring == b'\x00' else False

示例用法:

your_byte_string = b'\x00'
# you can write also
# your_byte_string = u'\u0000'

print(json.dumps(convert_to_bool(your_byte_string))) 

# >>> true

your_byte_string = b'\x01'
# you can write also
# your_byte_string = u'\u0001'

print(json.dumps(convert_to_bool(your_byte_string)))

# >>> false

然后,如果该字段为真,最终您可能希望添加一些代码来显示图像。这可以在服务器端或客户端完成。

服务器端

如果您不打算在 javascript 代码中使用布尔变量,您可以直接发送预期的 HTML:

if convert_to_bool(your_byte_string):
    # here I'm just printing it but you should use the dumped string as a json response
    print(json.dumps('The field is <b>true</b>!'))
else:
    print(json.dumps('Unfortunately the field is <b>false</b>.'))

客户端

如果您使用的是 json,我想您知道该怎么做,它是基本的 javascript,但是为了完整起见,这里是代码:

// javascript code
// yourdata is the field value, retrieved by the ajax call 

if (yourdata) {
    alert('The field is true!');    
} else {
    alert('The field is false!');
}
于 2013-02-09T07:57:52.500 回答