Jinja2 和 Javascript 访问 HTML 元素时出现引用错误
Jinja2 and Javascript Reference Error when accessing HTML elements
我正在尝试在 Flask 中创建一个表单,当用户单击 table 中的一个对象时,一个只读表单会填充与该对象相关的值。
我遇到的问题是,当我将该内容值 {{user.content}}
传递给将更新表单的 Javascript 时,我收到错误 Uncaught ReferenceError: foo is not defined
,其中 foo == user.content
.
除了我的值作为变量对象而不是字符串传递之外,我不确定这里发生了什么。我试过像这样转换成一个字符串:
onclick="displayResponse({{user.content|string}})"
但这似乎没有任何区别。知道我该如何纠正这个问题吗?
JS 本身是正确的,如果我对表单更新的值进行硬编码。
<div class="form-group">
<label for="exampleFormControlTextarea1">Response Data</label>
<textarea class="form-control" id="response-form-output" placeholder="root" rows="3" readonly></textarea>
</div>
{% for user in users %}
<tr>
<td>
<button type="button" class="btn btn-primary" onclick="displayResponse({{user.content}})">{{user.name}}</button>
</td>
<td>
{{user.content}}
</td>
<script type="text/javascript">
function displayResponse(data) {
document.getElementById("response-form-output").value=data;
}
</script>
</tr>
{% endfor %}
Jinja2 不知道变量的实际上下文,它只是用它的值替换变量。确保生成的源代码具有正确的语法是您的工作。在您的情况下,displayResponse
JS 函数需要一个字符串参数,因此我们需要生成一个:
<button type="button" class="btn btn-primary" onclick="displayResponse('{{user.content}}')">{{user.name}}</button>
如果 user.content
例如“测试字符串”,则变成:displayResponse('test string')
。如果没有撇号,JS 会尝试获取 non-existing test
和 string
变量。还要确保用相应的 HTML 实体替换 user.content
中的每个撇号,否则会产生语法错误。
我正在尝试在 Flask 中创建一个表单,当用户单击 table 中的一个对象时,一个只读表单会填充与该对象相关的值。
我遇到的问题是,当我将该内容值 {{user.content}}
传递给将更新表单的 Javascript 时,我收到错误 Uncaught ReferenceError: foo is not defined
,其中 foo == user.content
.
除了我的值作为变量对象而不是字符串传递之外,我不确定这里发生了什么。我试过像这样转换成一个字符串:
onclick="displayResponse({{user.content|string}})"
但这似乎没有任何区别。知道我该如何纠正这个问题吗?
JS 本身是正确的,如果我对表单更新的值进行硬编码。
<div class="form-group">
<label for="exampleFormControlTextarea1">Response Data</label>
<textarea class="form-control" id="response-form-output" placeholder="root" rows="3" readonly></textarea>
</div>
{% for user in users %}
<tr>
<td>
<button type="button" class="btn btn-primary" onclick="displayResponse({{user.content}})">{{user.name}}</button>
</td>
<td>
{{user.content}}
</td>
<script type="text/javascript">
function displayResponse(data) {
document.getElementById("response-form-output").value=data;
}
</script>
</tr>
{% endfor %}
Jinja2 不知道变量的实际上下文,它只是用它的值替换变量。确保生成的源代码具有正确的语法是您的工作。在您的情况下,displayResponse
JS 函数需要一个字符串参数,因此我们需要生成一个:
<button type="button" class="btn btn-primary" onclick="displayResponse('{{user.content}}')">{{user.name}}</button>
如果 user.content
例如“测试字符串”,则变成:displayResponse('test string')
。如果没有撇号,JS 会尝试获取 non-existing test
和 string
变量。还要确保用相应的 HTML 实体替换 user.content
中的每个撇号,否则会产生语法错误。