【发布时间】:2014-10-09 19:05:17
【问题描述】:
我们需要从 Javascript 运行 python 脚本。我们必须将输入字符串作为参数传递给 Python 脚本,并将 Python 输出显示到我们的网页上。
这是 Python 代码,当我在我的 linux 机器中运行此代码时,此代码可以正常工作:./sample.py 12345,给出输出 12345 和 ./sample.py 将显示 no argument found
#!/usr/bin/env python
import os
import sys
if len(sys.argv) > 1:
output = sys.argv[1]
else:
output = "no argument found"
print "Hello World!!!"
print output
如何从上述 python 的 ajax 调用中访问“参数”,并将该值用作参数?
Javascript:
$.ajax({
type: 'POST',
url: "scripts/sample.py",
data: {param: xyz}, //passing some input here
dataType: "text",
success: function(response){
output = response;
alert(output);
}
}).done(function(data){
console.log(data);
alert(data);
});
任何帮助将不胜感激。
编辑
按照建议,我正在尝试使用 CGI 让我的代码正常工作。
#!/Python34/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
data= cgi.FieldStorage()
# Get data from fields
output = data["param"]
# This will print to stdout for testing
print("Hello World!!!")
print(output)
每当运行 Ajax 调用时,响应为:[object HTMLDivElement],在 Firebug 中打开时会显示 Python 脚本的整个文本。我在这里错过了什么?
【问题讨论】:
-
你需要你的 python 接受 http 请求,而不是控制台解释
-
如何将参数值从 Ajax 获取到 Python 中?如果我的问题太“基本”,请道歉。
-
您要么需要设置一个小型网络服务器(使用 Flask 或 Django 之类的东西),要么可能使用 cgi 之类的东西来获取 post 参数。
-
你应该让你的服务器执行python脚本,阅读这个文档docs.python.org/2/howto/webservers.html
-
@snotwaffle 我按照您的建议添加了答案。谢谢。
标签: javascript jquery python ajax parameter-passing