栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Flask Button运行Python而无需刷新页面?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Flask Button运行Python而无需刷新页面?

我将其分为两条路线,以使您更轻松地了解所要做的事情:

LEFT, RIGHT, UP, DOWN, RESET = "left", "right", "up", "down", "reset"AVAILABLE_COMMANDS = {    'Left': LEFT,    'Right': RIGHT,    'Up': UP,    'Down': DOWN,    'Reset': RESET}@app.route('/')def execute():    return render_template('main.html', commands=AVAILABLE_COMMANDS)@app.route('/<cmd>')def command(cmd=None):    if cmd == RESET:       camera_command = "X"       response = "Resetting ..."    else:        camera_command = cmd[0].upper()        response = "Moving {}".format(cmd.capitalize())    # ser.write(camera_command)    return response, 200, {'Content-Type': 'text/plain'}

然后,在模板中,您只需要使用一些Javascript发送请求即可:

{# in main.html #}{% for label, command in commands.items() %}    <button  value="{{ command }}">        {{ label }}    </button>{% endfor %}{# and then elsewhere #}<script>// only run what comes next *after* the page has loadedaddEventListener("DOMContentLoaded", function() {  // Grab all of the elements with a class of command  // (which all of the buttons we just created have)  var commandButtons = document.querySelectorAll(".command");  for (var i=0, l=commandButtons.length; i<l; i++) {    var button = commandButtons[i];    // For each button, listen for the "click" event    button.addEventListener("click", function(e) {      // When a click happens, stop the button      // from submitting our form (if we have one)      e.preventDefault();      var clickedButton = e.target;      var command = clickedButton.value;      // Now we need to send the data to our server      // without reloading the page - this is the domain of      // AJAX (Asynchronous Javascript And XML)      // We will create a new request object      // and set up a handler for the response      var request = new XMLHttpRequest();      request.onload = function() {          // We could do more interesting things with the response          // or, we could ignore it entirely          alert(request.responseText);      };      // We point the request at the appropriate command      request.open("GET", "/" + command, true);      // and then we send it off      request.send();    });  }}, true);</script>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647061.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号