JavaScript向Flask传参异常:除title外参数为None的问题
Hey there! Let's break down why your category and content parameters are showing up as None in Flask, and how to fix this issue quickly.
问题根源:HTML实体编码的干扰
Looking at your request log, the key clue is the & strings instead of plain & between parameters:
127.0.0.1 - - [09/Aug/2020 21:53:09] "GET /modify?title=2+입니다&content=2고요&category=데이터 HTTP/1.1" 200 -
This happens because Jinja2 (Flask's templating engine) automatically escapes HTML special characters by default to prevent cross-site scripting (XSS) attacks. The & character in the URL generated by url_for gets converted to the HTML entity &—which is safe for HTML contexts, but breaks URL parameter parsing.
When the browser sends this request, Flask interprets the parameters like this:
title=2+입니다(this works fine)amp;content=2고요(it looks for a parameter namedamp;content, notcontent)amp;category=데이터(same issue—looking foramp;categoryinstead ofcategory)
Since those misnamed parameters don't exist, request.args.get() returns None for category and content.
解决方案:用safe过滤器禁用转义
To fix this, you need to tell Jinja2 not to escape the output of url_for when using it in a JavaScript context. Just add the |safe filter to your url_for call in the script:
function popupForModifying() { let option = "width=820, height=400, toolbar=no, menubar=no, location=no, directories=no, status=no, scrollbars=yes, resizable=no"; window.open("{{ url_for('modify', content=content[2], title=content[0], category=content[4])|safe }}", "", option); }
The safe filter marks the generated URL string as "safe" for rendering without escaping, so the & characters will stay as & instead of being converted to &.
验证修改效果
After making this change, your request log should show a clean URL with regular & separators:
127.0.0.1 - - [DD/Mon/YYYY HH:MM:SS] "GET /modify?title=2+입니다&content=2고요&category=데이터 HTTP/1.1" 200 -
Now Flask's request.args.get('category') and request.args.get('content') will correctly retrieve the values you passed from the template.
内容的提问来源于stack exchange,提问作者Suhyeon CHOI

