问题描述
如何从javascript读取数组到jinja模板:
how do i read an array from javascript to jinja template:
<script type="text/javascript">
var x =0;
function ActionDeterminator() {
x=x+1;
document.getElementById("me").innerHTML=x;
var $label = $('input[id = optionD]').next();
$label.text(x);
alert('{{option_D[0]}}');
return true;
}
</script>>
当我使用上面的代码时..它工作得很好.但是当我想像这样放置变量x时:
when i use the code above.. it works pretty well.but when i want to put the variable x like this:
<script type="text/javascript">
var x =0;
function ActionDeterminator() {
x=x+1;
document.getElementById("me").innerHTML=x;
var $label = $('input[id = optionD]').next();
$label.text(x);
alert('{{option_D[x]}}');
return true;
}
</script>>
我得到一个空的警报对话框.谁能告诉我如何解决这个问题
i get an empty alert dialog. can anyone tell me hw to fix this pls
推荐答案
您应该能够意识到,在'{{option_D[x]}}'
中,整个表达式都由Jinja评估,然后才到达浏览器,而Jinja一无所知关于x
是什么.
You should be able to realize that in '{{option_D[x]}}'
, the entire expression is being evaluated by Jinja, before it ever gets to the browser, and Jinja knows nothing about what x
is.
相反,您应该让Jinja将整个列表输出为JS数组,然后获取Javascript进行元素选择:
Instead, you should get Jinja output the entire list as a JS array, and then get the Javascript to do the element selection:
alert({{ option_D }}[x]);
在将其发送到模板之前,您可能需要在服务器端将option_D
转换为JSON.
You will probably need to convert option_D
to JSON at the server side before sending it to the template for this to work.
这篇关于从javascript到jinja的访问数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!