如何用javascript从html文件中触发python中的变量/方法

How to trigger a variable/method in python from a html file with javascript

本文关键字:python 变量 方法 javascript html 文件 何用      更新时间:2023-09-26

我想有一个html页面上的超链接运行在我的python文件中定义的变量。变量将清空数据库。这是我试图使用的代码。

Python

@app.route('/log')
def log():
cleardb = db.session.delete()
return render_template('log.html', cleardb=cleardb)

<a onclick="myFunction()">Clear database</a>
Javascript

<script>
function myFunction()
</script>

我不知道我需要什么javascript来运行变量。我想让cleardb得到触发,以便它将删除数据库。

谢谢

您需要使用javascript向/log发出ajax请求,它看起来像这样:

function myFunction() {
  var xmlhttp = new XMLHttpRequest();
   xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
          if (xmlhttp.status == 200) {
              //Do Success functionality here
          }
          else if (xmlhttp.status == 400) {
            //Handle 400 errors here
          }
          else {
            //All other errors go here
          }
       }
   };
   xmlhttp.open("GET", "/log", true);
   xmlhttp.send();
}