[英]Java script - given an string input, find if there is a variable with same name, if variable exist change value
[英]jquery prompted variable value given to python script
我有一个简单的问题,但我无法解决。 我有一个带选项的javascript表单,当用户选择一个选项时,系统会提示他们输入如下值:
var integer_value = window.prompt("What is the integer value?", "defaultText")
然后,我需要此整数值供python脚本使用。 因此,如果在我的python脚本中说:
integer_value = 2
它将需要更改为用户在提示窗口中输入的任何值。
下面的代码应满足您的需求。 可能有更好的方法可以做到这一点,但至少这种方法相当简单。
下次您遇到Web编程问题时,请告诉我们您正在使用什么服务器,什么框架以及jQuery或Ajax之类的JavaScript。 并发布我们可以实际运行的HTML / JavaScript和Python的代码的小型工作演示,以便我们可以准确地看到您在说什么。
首先,这是一个小的HTML / JavaScript页面,提示用户输入数据并将其发送到服务器。
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 & send" onclick="get_and_send_int()">
</p>
</body>
</html>
现在,对于CGI Python程序,该程序将接收数据并将其记录到文件中。 一个适当的程序将具有一些错误检查和数据验证,以及一种报告任何错误的方式。 Python CGI模块将使此任务更容易一些,但这不是绝对必要的。
Web服务器通常在名为cgi-bin的目录中查找CGI程序,通常将其用作程序的“当前工作目录”。 一个CGI程序不能在普通终端中运行:它的stdin和stdout本质上连接到调用该程序的Web页面,因此它打印的所有内容都被发送回该Web页面。 并且(取决于所使用的请求方法)它可以通过stdin从页面接收数据。
下面的程序不读stdin(如果尝试,它将似乎挂起)。 数据作为用于调用程序的URL的一部分发送给它,服务器提取该数据并将其放入CGI程序可以访问的环境变量中。
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()
将此程序保存到硬盘驱动器时,请确保已授予其执行权限。 由于您使用的是Flask,因此我假设您的服务器已配置为运行Python CGI程序,并且知道该程序在哪个目录中查找。
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.