javascript - 从我的网页访问 Flask 服务器

标签 javascript jquery python flask

这是一个从这个问题继续的问题 here .

我正在尝试使用网页上的图像按钮来控制伺服电机。我的伺服 Controller 采用 python 脚本 (cameraservo2.py) 的形式,我使用 jQuery 将数据post到 python 函数。我通过询问“如何从网页运行 python 脚本”得到的结论是使用“Flask”,这对我来说是全新的。不过,我仅使用 pip install Flask 就成功安装了它。 (如果我错过了什么,请告诉我?)

我的/var/www文件夹中有我的index.html、cameraservo3.py和routes.py。我的网络服务器默认运行,我可以从另一台网络计算机通过我的 Raspberry Pi IP 地址访问它。

这是我的routes.py代码:

from flask import Flask, jsonify, render_template, request
from cameraservo3 import turnCamera

app = Flask(__name__)

@app.route('/turn_servo', methods=['POST'])
def turn_servo_ajax():
    direction = request.form['direction']
    cam_result = turnCamera(direction=direction)
    return '<div> {} </div>'.format(cam_result)   

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0')

index.html 中我的 jQuery 脚本的一部分:

$('#left_button').click(function(){
            $.post("/turn_servo", {direction:"left"}).done(function (reply) {
                $('#camerapos').empty().append(reply);
                alert("left button clicked");});

        });

我的 html 的一部分:

<div id="control_button">
    <img src="button_left.png" id="left_button" height="50" width="50">
    <img src="button_right.png" id="right_button" height="50" width="50">
    <p id="camerapos"> test </p>
  </div>

cameraservo2.py 可以在 my question 的答案中找到那里。我运行 python paths.py 它给了我

 * Running on http://0.0.0.0:5000/
 * Restarting with reloader

但是当我单击 left_button 时,脚本(cameraservo2.py)不会被执行。怎么了?我哪部分做错了??

Flask 的快速入门指南也不是很有帮助。 :/

最佳答案

您将遇到 same-origin policy除非您从同一主机和端口号提供 index.html 文件。最简单的方法是将 index.html 页面也添加到 Flask 服务器中。

添加一个 / 路由,为执行 AJAX 发布的页面提供服务。您可以使用模板在此处填写 $.post() 的路线。如果使用 Jinja2 作为模板,则为:

@app.route('/')
def homepage():
    return render_template('index.html')

以及 Flask 项目的 templates 子目录中的文件 index.html:

$('#left_button').click(function(){
        $.post("{{ url_for('turn_servo_ajax') }}", {direction:"left"}).done(function (reply) {
            $('#camerapos').empty().append(reply);
            alert("left button clicked");});

    });

其中 {{ }} 部分是 Jinja2 模板语法,并且 url_for()返回 turn_servo_ajax View 函数的完整 URL。

关于javascript - 从我的网页访问 Flask 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22141570/

相关文章:

javascript - 如何检测用户何时在输入类型数字中键入字符串?

javascript - 如何使用highchart绘制下面的图表?

javascript - 如何使用 jquery/javascript 访问外部变量

python - 一系列的集合操作

javascript - 使用javascript动态更改div标签的位置

javascript - 组件返回失败代码 : 0x80040111 (NS_ERROR_NOT_AVAILABLE)

Python Sphinx 自动摘要 : failed to import module

python - 将套接字从 python 发送到 Meteor (node.js)

javascript - 带有非常简单 slider 的多个 slider

javascript - 微小的滚动条不适用于 javascript(javascript 冲突)