我在表格中有地址栏。我将表单转换为json后发送到Web服务器。出乎意料的是,当用户在地址字段中输入文本'X' Road
时,正在使用\
进行转义。我将该信息保存在数据库中,然后发送回客户端。jresp = '{% autoescape on%}{{jresp}}{% endautoescape %}';
但不幸的是,此处未显示转义字符。遇到文本'X Road'
时,标签关闭
这是代码段...
jresp =
'{"data":
{"alt_mobile": "7396623933", "father": "Janaiah", "gender": true, "surname": "Boddu",
"mobile": "9010101046", "religion": "Hindu", "mother": "Parvathi",
"address": "Khammam 'X' Road, Road No: 5", "dob": "14 July, 1995",
"cast": "Bc - B", "lastname": "Sai ", "temp_address": "Hyderabad",
"firstname": "Gowtham", "mother_maiden_name": "Mothukuri"},
"rollno": "12261A0109", "academics":
{"mtech_pref": 2, "abckl_total": 0,
"aieeerank": 44978, "engg_t_agg": 69.32,
"job_pref": 1, "sem4_total": 750, "sem1_pbckl": 0,
"verify": false, "sem7_pbckl": 0,
"x2class_year_of_pass": 2012, "sem2_abckl": 0,
"x2class_board": "BIEAP", "sem8_marks": 0,
"xclass_total": 700, "sem3_total": 750,
"x2class_t_agg": 89.8, "ms_pref": 3, "sem5_abckl": null,
"sem4_marks": 515, "x2class_total": 1000, "sem2_marks": 545,
"sem6_pbckl": 0, "sem3_pbckl": 0, "evaluation_test": false,
"sem5_pbckl": null, "pbckl_history": true, "sem6_total": 0,
"is_icse": false, "is_inter": true,
"abckl_history": false, "sem8_pbckl": 0, "comp_xclass_t_agg": 3,
"is_ssc": false, "sem1_total": 1000, "x2class_name": "CVR",
"x2class_marks": 898, "branch": 1, "sem6_abckl": 0,
"xclass_t_agg": 89.71, "sem1_abckl": 0, "pbckl_total": 0,
"xclass_name": "SVVN", "sem8_total": 0, "xclass_marks": 628,
"sem4_abckl": 0, "sem2_pbckl": 0, "mba_pref": 4,
"sem7_marks": 0, "sem6_marks": 0, "xclass_year_of_pass": 2010,
"sem7_abckl": 0, "sem2_total": 750, "sem7_total": 0,
"comp_x2class_t_agg": 3, "sem4_pbckl": 0,
"comp_engg_t_agg": 2, "sem1_marks": 693, "is_isce": null,
"sem3_marks": 500, "sem3_abckl": 0, "sem5_marks": null,
"xclass_board": "SSC", "task_reg": false, "cetrank": 23592,
"sem8_abckl": 0, "sem5_total": null}}';
它不应该引发错误,但是控制台中出现错误!
问题:
该如何解决?
到底是什么引起了该问题?
最佳答案
autoescape
标记转义特殊的HTML字符(<
和>
),而不是单引号。
如果要转义单引号,可以编写custom template filter。
例如:
from django import template
register = template.Library()
@register.filter
def escape_single_quotes(string):
# The two backslashes are interpreted as a single one
# because the backslash is the escaping character.
return string.replace("'", "\\'")
如果您不希望使用模板过滤器,则可以执行以下操作:
{# Note the type is not "text/javascript" so the browser does not try to interpret the content. #}
<script id="jresp" type="application/json">{{ jresp }}</script>
<script>
var jsresp = document.getElementById('jsreps').innerHTML;
</script>
第二种解决方案是更好的做法,因为您没有使用Django渲染JS,这意味着可以将其移动到外部文件中。
关于python - Django |自动退出开/关|单引号| JSON格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35157190/