我们需要从 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 调用访问“param”,并将该值用作参数?
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 脚本的整个文本。我在这里缺少什么?
最佳答案
您的 Ajax 调用将是对 python 脚本的 Web 请求 (http)
,因此您的 python 脚本需要在端口上监听此类请求并响应。
推荐使用上述方法,使用简单web server在你的样本中,py 或者你可以使用现有的,比如 Flask(或许多其他的)。
仅供引用 - 对于简单的任务,我不推荐 Django(它是一个大而重的网络框架,有很多你不需要的铃铛)。
关于javascript - 从 AJAX 或 JQuery 运行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336688/