【问题标题】:How to communicate between JavaScript and Python in a CGI script如何在 CGI 脚本中的 JavaScript 和 Python 之间进行通信
【发布时间】:2018-01-17 22:37:51
【问题描述】:

我有一个在本地主机上运行的 CGI 脚本。它有一个名为 compute(argument 1) 的 Python 函数并打印 html 标记以及一个名为 onClick 的 JavaScript 函数,该函数在浏览器上单击按钮时被调用。我不确定如何在这里 JavaScript 和 Python 之间进行通信。

这是 CGI 文件的 sn-p

   import cgi

   def worker():
      #Does something here and returns an python list called data
   def compute(index) 
       #Does something with data[index] and returns another python list called data2
   print ("Content-type: text/html")
   print ()
   print ("<html>")
   print ("<head>")
   print ("<title>Worker</title>")
   print("""<script type = "text/javascript">
   var count = 0;
   function onClick(){
    count = count+1;
     document.getElementById("dis").innerHTML = count; 
    };
  </script>""")
   print ("</head>")
   print ("<body>")
  <button  type = "button" class  = "next" onclick = "onClick()" >Next &rarr; </button>
   print("""Count: <p id = "dis" > 0 </p>""")
   print ("</body>")
   print ("</html>")

我的问题是如何让 JavaScript 函数 OnClick() 调用 Python 函数 compute(),方法是将变量计数作为参数传递,然后将 compute() 返回的结果列表存储为 JavaScript 变量。如果不需要再次调用工作函数会更好。甚至可以在 compute(index) 中返回单个变量而不是 python 列表并将其传递给 JavaScript。在此先感谢:)。

【问题讨论】:

  • 客户端 (javascript) 和服务器 (pythin) 之间的任何“通信”通常使用 AJAX(XMLHttpRequest 或客户端获取)完成

标签: javascript jquery python html cgi


【解决方案1】:

AJAX/JQUERY 可以将数据(例如 JSON)发送到您的 python 端点。但是您的脚本不是服务器。你需要一个服务器,也就是像 apache 这样的中间件。通过 AJAX POST 到您的服务器地址:

    $(function(){
    $.ajax({
    url: "ServerAdress/cgi-bin/" + service.py,
    type: "POST",
    async:true,
    data: {key_vehicule: 'mercedes'},
    success: function(response){

        },
    error: function(){

        },
    complete: function(){

        }
    });

确保将您的服务器配置为使用 python interpeter 执行 python 脚本,并获得所需的所有权限。在python脚本中,只导入cgi是不够的,需要接收数据:

     form = cgi.FieldStorage()
     vehicule = form.getvalue('key_vehicule')

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    相关资源
    最近更新 更多