如何将 python 变量的值(字符串)分配为 JavaScript 变量中的值

我想将从上一页通过 Python-CGI 获取的电子邮件和密码值分配给 JavaScript 变量。当我执行以下代码时,出现以下错误,


代码:


#!/usr/bin/python3

import cgi

import cgitb; cgitb.enable()

print ("Content-type:text/html\n\n")

form = cgi.FieldStorage()


email=str(form.getvalue("email")[0])

password=str(form.getvalue("password")[0])


print (email,password)  # email@email.com,123456


print ("""

<!DOCTYPE html>

<html>

  <body>


    <script>

      var email=String("""+str(email.strip())+""");

      var password=String("""+str(password.strip())+""");

      alert(email);

      alert(password);

    </script>


  </body>

</html>


""")

错误:


Uncaught SyntaxError: missing ) 在参数列表之后


繁花不似锦
浏览 152回答 2
2回答

慕的地8271018

尝试使用f-stringemail = 'jack@jack.com'password = 'secret'val1 = 133html  = f"""<!DOCTYPE html><html>  <body>    <script>      var email='{email.strip()}';      var password='{password.strip()}';      var data={{'key1':{val1}}};      alert(email);      alert(password);    </script>  </body></html>"""print(html)输出<!DOCTYPE html><html>  <body>    <script>      var email='jack@jack.com';      var password='secret';      var data={'key1':133};      alert(email);      alert(password);    </script>  </body></html>

跃然一笑

您必须在用户输入前后添加引号/双引号:因为最后,如果不添加 '',代码将像这样 String(email@gmail.com); 所以你必须添加引号/双引号#!/usr/bin/python3import cgiimport cgitb; cgitb.enable()print ("Content-type:text/html\n\n")form = cgi.FieldStorage()email=str(form.getvalue("email")[0])password=str(form.getvalue("password")[0])print (email,password)&nbsp; # email@email.com,123456print ("""<!DOCTYPE html><html>&nbsp; <body>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; var email=String('"""+str(email.strip())+"""');&nbsp; &nbsp; &nbsp; var password=String('"""+str(password.strip())+"""');&nbsp; &nbsp; &nbsp; alert(email);&nbsp; &nbsp; &nbsp; alert(password);&nbsp; &nbsp; </script>&nbsp; </body></html>""")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript