python的post函数_如何从jquery post执行python函数

I would like to call a python function when an image (button) is clicked which would allow me to control the servo from the web interface.

Here is part of my jQuery code:

$('#left_button').click(function(){

$.post("cameraservo2.py", {direction:"left"}).done(function (reply) {

$('#camerapos').empty().append(reply);

alert("left button clicked");});

});

And this is my Python code:

#!/usr/bin/python

def index (self, **data):

import pigpio

import time

servos=4

key = data['direction']

m=1500

while (m >= 500 and m <= 2500):

if (key =="left"):

m=m+100

elif (key =="right"):

m=m-100

pigpio.start()

pigpio.set_servo_pulsewidth(servos, m)

servostatus= "Servo {} {} micro pulses".format(servos[0], key, m)

print servostatus

time.sleep(1)

pigpio.stop()

return servostatus

My problem is when the button is clicked, it will alert "left button is clicked" which means it has run through the python file. But instead of showing the "servostatus", i get the whole python code displayed in my #camerapos div.

Please let me know if i need to post more information. Thanks!!

解决方案

You need some additional tools in order to call server side python code from client side query. Flask, a lightweight python web framework is often the tool of choice for problems like this.

To use POST with Flask/Jquery, you must annotate the receiving method in python. Your code would look something like this.

@app.route('/servo_pos', method=["POST"])

def servo_pos():

do_your_work_here

return jsonify({"servo_pos", ret_val})

You'll also need to tweak your jquery a bit.

$('#left_button').click(function(){

$.post("/servo_post", {direction:"left"}).done(function (reply) {

$('#camerapos').empty().append(reply);

alert("left button clicked");});

});

I'm not sure about this step, but you may also need to replace .post with .ajax. Since you don't want the page to reload before you display the new contents, this isn't a traditional post request, but rather an ajax one.

Alternatively, is there a reason that you MUST be using a post request, and a GET_JSON won't work, like in the jquery ajax pattern above?

Key notes:

add `methods=['POST']

data request argument is found in data.request.data

return data in a "jsonified" dictionary requires from Flask import jsonfiy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值