【发布时间】:2014-04-04 04:40:15
【问题描述】:
这是从这个问题here继续的问题。
我正在尝试使用我网页上的图像按钮来控制伺服电机。我的伺服控制器采用 python 脚本 (cameraservo2.py) 的形式,我使用 jQuery 将 post 数据传递给 python 函数。我从询问“如何从网页运行 python 脚本”得到的结论是使用“Flask”,这对我来说是全新的。但是我只使用pip install Flask 成功安装了它。 (如果我错过了什么,请告诉我?)
我的index.html, cameraservo3.py and routes.py 在我的/var/www文件夹中。我的网络服务器默认运行,我可以通过我的 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 routes.py 它给了我
* Running on http://0.0.0.0:5000/
* Restarting with reloader
但是当我单击 left_button 时,脚本 (cameraservo2.py) 没有被执行。怎么了?我做错了哪一部分??
Flask 的快速入门指南也不是很有帮助。 :/
【问题讨论】:
-
将
your_cam_function替换为turnCamera。turnCamera应该是要调用的函数。 -
在你的 DOM 中实际上是否有一个 ID 为
left_button的元素?它出现在 DOM 中此脚本之前还是之后? DOM中是否有ID为camerapos的元素?查看index.html模板的关键部分会有所帮助:-) -
@msvalkon 很抱歉这个错误。是的,我确实在我的代码中使用了
turnCamera,但仍然没有任何反应。我怀疑我的问题可能与 :5000 端口有关……但我该如何解决问题出在哪里? -
您还需要从烧瓶服务器加载
index.html页面;您可以将其设置为静态页面或/的新路由,以返回脚本。否则你会遇到same origin policy 违规;http://localhost/的页面不允许使用 AJAX 发布到http://localhost:5000(不同的端口号)。 -
@SeanVieira 是的,我愿意。如上所述更新了我的问题。 :) 它在脚本之后。
标签: javascript jquery python flask