简体   繁体   中英

jquery prompted variable value given to python script

I have what I think to be a simple problem, but I cannot figure out the solution. I have a javascript form with options, and when the user selects an option they get prompted to input a value as below:

var integer_value = window.prompt("What is the integer value?", "defaultText")

I then need this integer value to be used by a python script. So, if say in my python script:

integer_value = 2

It would need to change to whatever value the user inputs in the prompt window.

The code below should do what you need. There may be better ways to do this, but at least this way is fairly simple.

Next time you have a Web programming question, tell us what server you're using, and what framework, and any JavaScript things like jQuery or Ajax. And post a small working demo of your code, both the HTML/JavaScript and the Python, that we can actually run so we can see exactly what you're talking about.

Firstly, here's a small HTML/JavaScript page that prompts the user for data and sends it to the server.

send_to_python.html

<!DOCTYPE html>
<html>
<head><title>Send data to Python demo</title>

<script>
function get_and_send_int()
{
    var s, integer_value, default_value = 42;
    s = window.prompt("What is the integer value?", default_value);
    if (s==null || s=='')
    {
        alert('Cancelled');
        return;
    }

    //Check that the data is an integer before sending
    integer_value = parseInt(s);
    if (integer_value !== +s)
    {
        alert(s + ' is not an integer, try again');
        return;
    }

    //Send it as if it were a GET request.
    location.href = "cgi-bin/save_js_data.py?data=" + integer_value;
}
</script>
</head>

<body>
<h4>"Send data to Python" demo</h4>
<p>This page uses JavaScript to get integer data from the user via a prompt<br>
and then sends the data to a Python script on the server.</p>

<p>Click this button to enter the integer input and send it.<br>
<input type="button" value="get &amp; send" onclick="get_and_send_int()">
</p>

</body>
</html>

And now for the CGI Python program that receives the data and logs it to a file. A proper program would have some error checking & data validation, and a way of reporting any errors. The Python CGI module would make this task a little easier, but it's not strictly necessary.

The Web server normally looks for CGI programs in a directory called cgi-bin, and that's generally used as the program's Current Working Directory. A CGI program doesn't run in a normal terminal: its stdin and stdout are essentially connected to the Web page that invoked the program, so anything it prints gets sent back to the Web page. And (depending on the request method used) it may receive data from the page via stdin.

The program below doesn't read stdin (and will appear to hang if you try). The data is sent to it as part of the URL used to invoke the program, and the server extracts that data and puts it into an environment variable that the CGI program can access.

save_js_data.py

#! /usr/bin/env python

''' save_js_data

    A simple CGI script to receive data from "send_to_python.html" 
    and log it to a file
'''

import sys, os, time

#MUST use CRLF in HTTP headers
CRLF = '\r\n'

#Name of the file to save the data to.
outfile = 'outfile.txt'

def main():
    #Get the data that was sent from the Web page
    query = os.environ['QUERY_STRING']

    #Get the number out of QUERY_STRING
    key, val = query.split('=')
    if key == 'data':
        #We really should check that val contains a valid integer

        #Save the current time and the received data to outfile
        s = '%s, %s\n' % (time.ctime(), val)
        with open(outfile, 'a+t') as f:
            f.write(s)

    #Send browser back to the refering Web page
    href = os.environ['HTTP_REFERER']
    s = 'Content-type: text/html' + CRLF * 2
    s += '<meta http-equiv="REFRESH" content="0;url=%s">' % href
    print s


if __name__ == '__main__':
    main()

When you save this program to your hard drive, make sure that you give it execute permissions. Since you're using Flask, I assume your server is configured to run Python CGI programs and that you know what directory it looks in for such programs.

I hope this helps.

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