单击按钮时执行 python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15151133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute a python script on button click
提问by user2058205
I have an HTML page with one button, and I need to execute a python script when we click on the button and return to the same HTML page with the result.
我有一个带有一个按钮的 HTML 页面,当我们单击该按钮并返回到同一个 HTML 页面并返回结果时,我需要执行一个 python 脚本。
So I need do some validation on return value and perform some action.
所以我需要对返回值进行一些验证并执行一些操作。
Here is my code:
这是我的代码:
HTML:
HTML:
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue"></button>
JS:
JS:
function validate(){
if (returnvalue=="test") alert(test)
else alert ("unsuccessful")
}
What my python code is doing is some validation on the name entered in the text box and gives the return status.
我的python代码正在做的是对文本框中输入的名称进行一些验证并给出返回状态。
But I need the result back on the same page, so I can do the form submission later with all the details. Any help will be appreciated
但是我需要在同一页面上返回结果,以便我可以稍后使用所有详细信息进行表单提交。任何帮助将不胜感激
回答by martriay
You can use Ajax, which is easier with jQuery
您可以使用 Ajax,使用jQuery更容易
$.ajax({
url: "/path/to/your/script",
success: function(response) {
// here you do whatever you want with the response variable
}
});
and you should read the jQuery.ajax pagesince it has too many options.
您应该阅读jQuery.ajax 页面,因为它有太多选项。
回答by Hari
Make a page(or a service) in python, which can accept post or get request and process the info and return back a response. It is better if the response is in json format. Then you can use this code to make a call on the button click.
在 python 中创建一个页面(或服务),它可以接受 post 或 get 请求并处理信息并返回响应。如果响应是 json 格式会更好。然后您可以使用此代码调用按钮单击。
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">
<script>
$('#id').click(function(){
$.ajax({
type:'get',
url:<YOUR SERVERSIDE PAGE URL>,
cache:false,
data:<if any arguments>,
async:asynchronous,
dataType:json, //if you want json
success: function(data) {
<put your custom validation here using the response from data structure >
},
error: function(request, status, error) {
<put your custom code here to handle the call failure>
}
});
});
</script>
I hope this helps
我希望这有帮助

