如何在JavaScript函数中访问Python对象?
这段话的意思是,现在我正在用Python编写代码,使用的是CherryPy和Genshi框架。借助这个框架,我可以把Python中的变量发送到HTML文件里,使用Genshi。但是我想在JavaScript函数中访问这个变量,我该怎么做呢?
HTML文件是:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:py="http://genshi.edgewall.org/">
<head>
<title>Home</title>
<script type="text/javascript">
function setparent(val) {
document.getElementById("tpar").value=val;
}
</script>
</head>
<body>
<div >
<table>
<div py:for="user in users">
<tr>
<td>
<div title="${user.userid}" onclick="setparent('${user.userid}')">${user.fname+" "+ user.lname}</div>
<py:if test="user.resource.__len__() > 0">
<div>
<py:for each="res in user.resource">
<div><a href="">${user.resource[res]}</a></div>
</py:for>
</div>
</py:if>
</td>
</tr>
</div>
</table>
</div>
</body>
</html>
我想在JavaScript函数中访问Python中的“users”变量。
你能告诉我怎么做吗?
1 个回答
1
从Python传值到JavaScript的正确方法是,特别是当这些值不仅仅是简单的数字或者非常有限的字符集时(基本上就是字母和数字,还有一些不带引号的符号),应该使用一个叫做JSON编码器的工具(json.dumps(...)
)。这样做可以确保这些值不会导致任何问题。