我希望在cherrypy中将变量信息从python环境共享到java脚本,如下所示:
class test(object):
@cherrypy.expose
def index(self):
variableX = 2016
return """<!DOCTYPE html>
<html>
<head>
<title>Set interval with two inputs</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<link rel="stylesheet" type="text/css" href="/static/codebase/dhtmlxcalendar.css"/>
<script src="/static/codebase/dhtmlxcalendar.js"></script>
<style>
input#date_from, input#date_to {
font-family: Tahoma;
font-size: 12px;
background-color: #fafafa;
border: #c0c0c0 1px solid;
width: 100px;
}
span.label {
font-family: Tahoma;
font-size: 12px;
}
</style>
<script>
var myCalendar;
function doOnLoad() {
myCalendar = new dhtmlXCalendarObject(["date_from","date_to"]);
// getting today info (start code)
var tomm = new Date();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {dd='0'+dd};
if(mm<10) {mm='0'+mm};
today = yyyy+'-'+mm+'-'+dd;
// getting today info (end code)
myCalendar.setDate(today);
myCalendar.hideTime();
// init values
var t = new Date();
byId("date_from").value = variableX ;
byId("date_to").value = variableX ;
}
function setSens(id, k) {
// update range
if (k == "min") {
myCalendar.setSensitiveRange(byId(id).value, null);
} else {
myCalendar.setSensitiveRange(null, byId(id).value);
}
}
function byId(id) {
return document.getElementById(id);
}
</script>
</head>
<body onload="doOnLoad();">
<form method="get" action="generate">
<div style="position:relative;height:280px;">
<span class="label">From</span> <input type="text" id="date_from" name="FirstDate" onclick="setSens('date_to', 'max');" readonly="true">
<span class="label">Till</span> <input type="text" id="date_to" name="LastDate" onclick="setSens('date_from', 'min');" readonly="true">
<button type="submit">Give it now!</button>
</form>
</div>
</body>
</html>"""
我试图在html中的javascript中获取variableX(即2016)的值。有什么想法吗?
答案 0 :(得分:0)
您只需要创建一个新的javascript变量,其值为variableX
。
在您的示例中添加以下行:
...
// getting today info (start code)
var variableX = """ + str(variableX) + """;
var tomm = new Date();
...
但我真的建议你学习如何使用像Jinja2这样的模板引擎,然后像这样创建一个index.html
模板:
...
// getting today info (start code)
var variableX = {{variabeX}};
var tomm = new Date();
...
你的python代码看起来像这样:
@cherrypy.expose
def index(self):
return jinja2env.get_template('index.html').render(variableX=2016)