我在使用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>')
答案 0 :(得分:2)
print('var x = {{temp}};') #Here's how I'm trying to assign the python variable.
看起来你正试图做一个模板事情而不是真正在模板引擎中。
请改为尝试:
print( 'var x =' + temp + ';' )
答案 1 :(得分:1)
许多方法可以做到这一点:
print ('var x = %d' % temp)
print ('var x = ' + str(temp) + ';')
print ('var x = {{temp}};'.replace("{{temp}}", str(temp)))