在按钮点击时执行Python脚本

15 投票
2 回答
77827 浏览
提问于 2025-04-17 17:32

我有一个HTML页面,上面有一个按钮。当我们点击这个按钮时,我需要执行一个Python脚本,并且返回到同一个HTML页面,显示结果。

所以我需要对返回的值进行一些验证,并执行相应的操作。

这是我的代码:

HTML:

<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue"></button>

JS:

function validate(){
    if (returnvalue=="test") alert(test)
    else alert ("unsuccessful")
}

我的Python代码主要是对文本框中输入的名字进行一些验证,并返回状态。

但是我需要在同一个页面上得到结果,这样我才能稍后提交表单,包含所有的细节。任何帮助都非常感谢。

2 个回答

12

用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>

希望这对你有帮助

15

你可以使用Ajax,这样做会更简单,尤其是用jQuery这个工具。

$.ajax({
   url: "/path/to/your/script",
   success: function(response) {
     // here you do whatever you want with the response variable
   }
});

而且你应该看看jQuery.ajax的页面,因为里面有很多选项可以选择。

撰写回答