简体   繁体   中英

How to communicate between JavaScript and Python in a CGI script

I have a CGI script which runs on local host. It has a Python function named compute(argument 1) and prints html tags along with a JavaScript function called onClick which gets called when a button is clicked on the browser. I am not sure how to communicate between JavaScript and Python here.

Here is a snippet of the CGI file

   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>")

My question here is how do I make the JavaScript function OnClick() call the python function compute() by passing variable count as a parameter and then storing the resulting list returned by compute() as a JavaScript variable. It would be better if worker function does not have to be called again. It would be fine to even return a single variable in compute(index) rather than a python list and pass it to JavaScript. Thanks in advance :).

AJAX/JQUERY can send the data, JSON for instance, to your python endpoint. But your script is not a server. You need a server aka middleware like apache. POST via AJAX to your server adress:

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

        },
    error: function(){

        },
    complete: function(){

        }
    });

Be sure to have your server configured to execute the python script with the python interpeter and all the right it needs. In the python script, just importing the cgi is not enought, you need the to receive the data:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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