单击javascript中的按钮运行python脚本
Run python script by clicking button in javascript
我想要的是运行python脚本,只需点击html页面中的按钮,并在我的页面上显示python代码结果。
因为这只是一个小项目,所以我不想过度学习Django或其他web框架,即使我知道它会起作用。
我做了一些搜索,ajax似乎是适合我的解决方案,但我不知道如何通过ajax执行python代码。我知道我可以使用以下代码通过ajax获取一些字符串:
function loadXMLDoc()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
}
提前感谢任何能提供帮助的人。
为了扩展@Liongold的评论,完整的工作流程如下:
这是如何发生的概述
- 按钮点击的javascript代码被执行。此代码是从浏览器在客户端上运行的
- AJAX请求通过互联网发送,就像HTTP请求一样,由运行Python代码的计算机上运行的web应用程序进行解释
- python代码创建一个响应,并将其格式化以发送回客户端
- javascript以纯文本形式读取响应,并决定它的含义和如何使用。JSON是一种非常流行的通过AJAX交换数据的格式
你需要做什么
任一:
- 学习服务器端python框架。烧瓶很轻,可能会做你想做的事。我在这里发现的最大障碍是处理交叉起源(CORS)问题。开始于http://flask.pocoo.org/docs/0.10/quickstart/
或
- 看看是否可以将python脚本移植到浏览器中。代码是否需要在特定的计算机(服务器)上运行,或者理论上可以转换为javascript并在网页中运行。如果语言差异是你唯一的问题,看看http://www.skulpt.org/
我遇到了一个类似的问题,经过几个小时的搜索,我就是这样解决的。假设html文件和python文件是同一个文件夹。
<script>
function runScript() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
alert('Successful .... ' + request.responseText);
} else {
alert('Something went wrong, status was ' + request.status);
}
}
};
request.open('POST', 'test.py', true);
request.send(null);
return false;
};
document.getElementById('script-button').onclick = runScript;
</script>
This goes to your html file
-----------------------------
<button type="button" id="script-button">
add this line at the top of your python file
---------------------------------------------
test.py
------------
#!C:'Python34'python.exe -u
print("Testing 123")
add this directive to httpd.conf (Apache)
-----------------------------------------
# "C:/xampp/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "C:/xampp/<path to your project on the web server>">
AllowOverride All
Options Indexes FollowSymLinks Includes ExecCGI
AddHandler cgi-script .py .pyc
Order allow,deny
Allow from all
Require all granted
</Directory>
相关文章:
- Meteor如何运行服务器端python脚本
- 运行 python 脚本并在网站上显示打印值
- 在HTML网页中运行python方法
- 在nodejs中运行Python脚本
- 单击javascript中的按钮运行python脚本
- 在 Mac OSX 10.11 上的 MAMP 3.5 上运行 python-script
- 在节点中运行 python 脚本.js语法错误
- 运行python SimpleHTTPServer时的Javascript和css文件搜索路径
- Python 进入一个网站并运行 $(document).ready(function()
- 无法在浏览器中运行 python Web 应用程序
- 使用html按钮运行python脚本
- 在JS中运行服务器端python:pico的困难
- 使用While True时,使用node js运行python脚本不起作用.keep-listen
- 如何通过Web服务器运行python脚本并将结果返回到javascript
- 使用ajax运行python脚本
- 从postgres函数中运行python或javascript文件
- 从AJAX或JQuery运行Python脚本
- 从Node.js中运行python脚本
- 如何使用adobeacrobat中的Javascript来运行Python脚本?
- 使用Flask使用javascript运行python脚本