繁体   English   中英

将Python变量分配给JavaScript变量

[英]Assign Python variable to JavaScript variable

我正在使用Python和CGI的网站上进行维护。 该站点当前在Python上运行,但是出于某些奇怪的原因,我必须将Python变量分配给同一Python文件上的JavaScript变量。 我尝试了很多事情,但没有成功,我不知道是否有可能这样做。 任何帮助将不胜感激。 我简化了代码,只是为了说明我需要做的从Python到JavaScript的变量交换。 我的Python版本是3.5.2,该站点正在IIS服务器上运行。 再次非常感谢您的帮助和时间。

import cgi

print('')
temp = 78 #These is the Python variable I need to assign to the Javascript variable.

print('<html>')
print('<script type="text/javascript">')
print('var x = {{temp}};') #Here's how I'm trying to assign the python variable.
print('document.write(x);')
print('document.write("HELLO PYTHON VARIABLE!!");')
print('</script>')
print('</html>')
print('var x = {{temp}};') #Here's how I'm trying to assign the python variable.

看起来您正在尝试执行模板操作,而实际上并没有使用模板引擎。

尝试以下方法:

print( 'var x =' + temp + ';' )

有很多方法可以做到这一点:

print ('var x = %d' % temp)

print ('var x = ' + str(temp) + ';')

print ('var x = {{temp}};'.replace("{{temp}}", str(temp)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM