按钮单击时执行python脚本

use*_*205 15 html javascript python ajax

我有一个带有一个按钮的HTML页面,当我们点击按钮并返回到带有结果的同一个HTML页面时,我需要执行一个python脚本.

所以我需要对返回值进行一些验证并执行一些操作.

这是我的代码:

HTML:

<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue"></button>
Run Code Online (Sandbox Code Playgroud)

JS:

function validate(){
    if (returnvalue=="test") alert(test)
    else alert ("unsuccessful")
}
Run Code Online (Sandbox Code Playgroud)

我的python代码正在做的是对文本框中输入的名称进行一些验证并给出返回状态.

但我需要将结果返回到同一页面,因此我可以稍后提交表单并提供所有详细信息.任何帮助将不胜感激

mar*_*iay 15

您可以使用Ajax,使用jQuery更容易

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

你应该阅读jQuery.ajax页面,因为它有太多选项.

  • 在我的例子中,此代码从文件URL下载python脚本文件 (4认同)

Har*_*ari 12

在python中创建一个页面(或服务),它可以接受发布或获取请求并处理信息并返回响应.如果响应是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>
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助