2017-01-13 205 views
0

我正在使用Python和CGI进行维护。该网站目前运行在Python上,但出于某种奇怪的原因,我必须将Python变量分配给 到同一个Python文件中的JavaScript变量。我尝试了很多东西,但他们都没有工作,我不知道是否有可能这样做。任何帮助将不胜感激。我简化了代码,以显示从Python到JavaScript的变量交换。我的Python版本是3.5.2,并且该站点在IIS服务器上运行。再次感谢您的帮助和时间。将Python变量分配给JavaScript变量

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

是它只是一个数字,或不变量保持用户输入? (因为那时涉及安全) – RemcoGerlich

回答

1

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

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

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

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

非常感谢GantTheWanderer!这只是我想交换的数字,两种方式都能完美运作!我有很多日子都陷入困境,你只是节省了很多时间,再次感谢你的回应。来自危地马拉的问候。 –

+0

De nada,编写程序编写程序起初可能会很棘手,但通过实践它成为第二天性。其他缺陷包括不得不处理报价(例如'temp =“Occam's Razor”''print(“var x ='”+ temp +“'”)''你可能会很快跟踪它们而遇到麻烦。 – GantTheWanderer

+0

Muchas gracias otra vez格兰特!哇,你是对的,它很难跟踪报价,我无法让你的字符串例子工作,但我没有考虑数数,我使用3.5版本,我认为,你的是2.7由于“奥卡姆剃刀”上的双引号,它就像这个'奥卡姆剃刀'用单引号工作,感谢字符串的例子,因为我现在只是偶然发现了这个问题,非常感谢! –

2
print('var x = {{temp}};') #Here's how I'm trying to assign the python variable. 

它看起来像你正在尝试做一个模板的事情,而不在模板引擎实际上是。

试试这个:

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

关于模板引擎的有效点 –

+0

非常感谢Evan Thompson!你完全正确,我需要这样做,同时,这些解决了即时问题,它非常完美,非常感谢你! –