简体   繁体   English

jQuery提示给python脚本的变量值

[英]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: 我有一个带选项的javascript表单,当用户选择一个选项时,系统会提示他们输入如下值:

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

I then need this integer value to be used by a python script. 然后,我需要此整数值供python脚本使用。 So, if say in my python script: 因此,如果在我的python脚本中说:

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. 下次您遇到Web编程问题时,请告诉我们您正在使用什么服务器,什么框架以及jQuery或Ajax之类的JavaScript。 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. 并发布我们可以实际运行的HTML / JavaScript和Python的代码的小型工作演示,以便我们可以准确地看到您在说什么。

Firstly, here's a small HTML/JavaScript page that prompts the user for data and sends it to the server. 首先,这是一个小的HTML / JavaScript页面,提示用户输入数据并将其发送到服务器。

send_to_python.html 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. 现在,对于CGI Python程序,该程序将接收数据并将其记录到文件中。 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. Python CGI模块将使此任务更容易一些,但这不是绝对必要的。

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. Web服务器通常在名为cgi-bin的目录中查找CGI程序,通常将其用作程序的“当前工作目录”。 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. 一个CGI程序不能在普通终端中运行:它的stdin和stdout本质上连接到调用该程序的Web页面,因此它打印的所有内容都被发送回该Web页面。 And (depending on the request method used) it may receive data from the page via stdin. 并且(取决于所使用的请求方法)它可以通过stdin从页面接收数据。

The program below doesn't read stdin (and will appear to hang if you try). 下面的程序不读stdin(如果尝试,它将似乎挂起)。 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. 数据作为用于调用程序的URL的一部分发送给它,服务器提取该数据并将其放入CGI程序可以访问的环境变量中。

save_js_data.py 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. 由于您使用的是Flask,因此我假设您的服务器已配置为运行Python CGI程序,并且知道该程序在哪个目录中查找。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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