- 1、ajax的使用,下面是基于webpy完成的例子:
- 后台相应代码:
class AjaxFriendReq:
def POST(self):
try:
i = web.input()
#要使用这个get来获取键对应的值,因为这样子其不会因为不存在这个键而导致抛异常,
#不存在的键其返回值是None
fri_req_to = i.get('fri_req_to')
fri_req_from = session.account
if(db.where('accounts', account=fri_req_to)[0]):
db.insert('friendrequst', fri_req_from=fri_req_from, fri_req_to=fri_req_to,req_on=time.time())
return "requst success"
except:
return "target id not exist"
注意:以后获取键的值最好用get函数。如果前端返回数据带有ID的话,则后台就可以根据这些ID进入不用的处理函数。并返回数据或者网页跳转。
- 前端相应代码:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script>
$(document).ready(function(){
$("#frireqbutton").click(function(){
$.ajax({
type: "POST",
url:"/ajaxfriendreq",
async:false,
dataType:"html",
data:{fri_req_to:$("#frireq").val()},
success:function(msg){
alert(msg);
$("#frireqfra").hide();
}
});
});
});
</script>
注意:如果后台返回的不是字符串,而是一个json包。则这里需要需要包dataType改为json。如下后台代码:
def POST(self):
if models.User().current_id() != None:
# 进行数据读取
inputs = web.input()
print(inputs.get('ID'))
testajax=inputs.get('ID')
if testajax!=None:
return json.dumps({'key1':'value1','key2':'value2'})
则前端可以使用:
function testajax() {
$.ajax(
{
type: "POST",
url: "/fundma",
async: true,
dataType: "html",
data: {ID: "my"},
success: function (msg) {
alert("zongchang :",msg.key3);
alert("data" + msg.key1);
alert("data"+msg.key2);
}
}
)
}
注意:其中的msg.key3读取的值时空,即不会报错。
其中前端的请求方式也可以改成如下:
$("button").click(function(){
$.post("/",
{
name:"Donald Duck",
city:"Duckburg"
},
function(data,status){
alert("Data: " + data.key1);
},"json");
});
其后台代码为:
class JsonTest:
def GET(self):
web.header('content-type','text/json')
return json.dumps({'key1':'value1','key2':'value2'})
下面时对应参数的解析:
参考博客:https://www.cnblogs.com/huiyuantang/p/5458278.html
2、webpy服务在img上显示图片:
- img上显示的图片可以是本地电脑其它盘里的图片,不过一般浏览器为了安全是静止进行加载其它位置的图片的,一般会报如下错误:
not allowed to load local resource
img加载的图片是web工程下的指定目录下的图片,如webpy的指定目录就是static文件目录。其结构如下:
其中i文件夹下放的就是自己需要显示的图片,html文件种需要显示的地方代码为:
<img src="/static/i/1.jpg" id="srcimg" alt="shanghai" width="112" height="112"/>
动态修改这个src显示的图片的javascript为(点击某个按钮进行这个刷新函数):
function messagebox() {
var img=document.getElementById('srcimg');
img.src="/static/i/1.jpg?"+Math.floor(Math.random()*99);
alert(img.src)
}
这个在地址后面跟个随机数是为了防止后台的1.jpg图片已经更改而前端的图片为刷新,因为浏览器会根据地址一样在本地缓存读取图片,导致刷新不了。
参考:https://www.jianshu.com/p/28afa05f6071
3、通过ajax修改table里的数据:
- 下面是一个控制表格比较好的方法:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="mytabletest.css" type="text/css">
<script language="javascript" type="text/javascript">
function $(id) {
return document.getElementById(id);
}
function addHero() {
var z;
var i=$("ph").value;
for (var j=1;j<$("mytable").rows.length;j++) {
if(parseInt(i)>=parseInt($("mytable").rows[j].cells[0].getElementsByTagName("input")[0].value))
{
z=j;
}
}
var tableRow=$("mytable").insertRow(z+1);
var Cell_0=tableRow.insertCell(0);
Cell_0.innerHTML='<input value="'+$("ph").value+'" readonly="true"/>';
Cell_0.className="s1";
var Cell_1=tableRow.insertCell(1);
Cell_1.innerHTML='<input value="'+$("xm").value+'" readonly="true"/>';
Cell_1.className="s2";
var Cell_2=tableRow.insertCell(2);
Cell_2.innerHTML='<input value="'+$("ch").value+'" readonly="true"/>';
Cell_2.className="s3";
var Cell_3=tableRow.insertCell(3);
Cell_3.innerHTML="<a href='#' onclick='Del(this.parentNode,this.parentNode.parentNode.rowIndex)'>删除</a>";
Cell_3.className="s4";
var Cell_4=tableRow.insertCell(4);
Cell_4.innerHTML="<a href='#' onclick='edit(this.parentNode.parentNode)' class='edit'>修改</a>";
Cell_4.className="s5";
}
function Del(obj,val) {
var a=window.confirm("您确定要删除吗?");
if(a) {
$("mytable").deleteRow(val);
} else {
window.alert("未删除!");
}
}
function edit(obj) {
var inp = obj.getElementsByTagName("input");
for (var i=0,len=inp.length;i<len;i++)
{
inp[i].readOnly=false;
}
}
</script>
</head>
<body>
<h1>梁山英雄排行榜</h1>
<table id="mytable" cellspacing="0px" border="3" bordercolor="red">
<tr>
<td class="s_top">排行</td>
<td class="s_top">姓名</td>
<td class="s_top">绰号</td>
<td class="s_top" colspan="2">操作</td>
</tr>
<tr>
<td class="s1"><input value="1" readonly="true"/></td>
<td class="s2"><input value="宋江" readonly="true"/></td>
<td class="s3"><input value="呼保义" readonly="true"/></td>
<td class="s4"><a href="#" onclick='Del(this.parentNode,this.parentNode.parentNode.rowIndex)'>删除</a></td>
<td class="s5"><a href="#" onclick='edit(this.parentNode.parentNode)'>修改</a></td>
</tr>
<tr>
<td class="s1"><input value="2" readonly="true"/></td>
<td class="s2"><input value="卢俊义" readonly="true"/></td>
<td class="s3"><input value="玉麒麟" readonly="true"/></td>
<td class="s4"><a href="#" onclick='Del(this.parentNode,this.parentNode.parentNode.rowIndex)'>删除</a></td>
<td class="s5"><a href="#" onclick='edit(this.parentNode.parentNode)'>修改</a></td>
</tr>
<tr>
<td class="s1"><input value="3" readonly="true"/></td>
<td class="s2"><input value="吴用" readonly="true"/></td>
<td class="s3"><input value="智多星" readonly="true"/></td>
<td class="s4"><a href="#" onclick='Del(this.parentNode,this.parentNode.parentNode.rowIndex)'>删除</a></td>
<td class="s5"><a href="#" onclick='edit(this.parentNode.parentNode)'>修改</a></td>
</tr>
</table>
<span class="span1">排行</span><input id="ph" type="text"/>
<br>
<span class="span1">姓名</span><input id="xm" type="text"/>
<br>
<span class="span1">绰号</span><input id="ch" type="text"/>
<br>
<input class="but" type="button" value="添加英雄" onclick="addHero()"/>
</body>
</html>
- 通过跟后台通信修改表格:
JavaScript代码为:
function checkstatus() {
$.ajax(
{
type: "POST",
url: "/Sckmaage",
async: true,
dataType: "json",
data: {requireID: "getstatus"},
success: function (msg) {
// alert("okh" + JSON.stringify(msg));
infoerror=msg.getinfoerror;
if (infoerror != undefined) {
alert("报错:" + msg.getinfoerror);
}
var tb = document.getElementById('status');
// alert("data" + msg.cpuPercent);
tb.rows[0].cells[0].innerHTML = msg.online;
tb.rows[0].cells[1].innerHTML = msg.cpuPercent;
tb.rows[0].cells[2].innerHTML = msg.curdate;
//报错,后面的代码不会执行
// tb.rows[0].cells[6].innerHTML = msg.curdate;
// alert("data3" + msg.online);
}
}
)
}
此时后台的post请求返回为:
return json.dumps(info)
其中undefined是当没有定义这个键值时返回的数据。
4、$.post():
$.post()是jquery自带的一个方法,使用前需要引入jquery.js,其语法为:
5、$.post(url,data,callback,type)与$("button").click;
其中url(必须):发送请求的地址,String类型 data(可选):发送给后台的数据,一般使用json格式,也可以直接使用一个str
callback(可选):请求成功后的回调函数, type:传输给后台的数据类型
下面是一个把当前点击的button的id传给后台:
#引入jquery
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(function(){
$("button").click(function(){
$.post("/cmd",this.id,function(data,status){});
//表示妞对应的ID值,会被传入到树莓派服务器中,就如同你在树莓派的命令行(cmd)中输入低的值
});
});
</script>
#定义了多个button,其都共同触发上面的button点击函数
<body>
<div>
<button id="front" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-up"></button>
</div>
<div>
<button id="left" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-left"></button>
<button id="right" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-right" style="margin-left:50px"></button>
</div>
<div>
<button id="rear" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-down"></button>
</div>
</body>
6、window.onload与mjpg_streamer
其是在页面加载完 后触发的,例如客服端上显示实时视频监控代码如下:
<script>
window.onload = function(){
var url = "http://"
#使用mjpg_streamer开启视频流服务
url += window.location.hostname; /* 获取锚点(“s#”后面的分段) */
url += ":8090/?action=stream";
//window.alert(typeof(url));
document.getElementById("cameraAddr").src = url;
//window.alert(url);
}
</script>
<body>
<img id='cameraAddr' src="h" style="--webkit-transform:rotate(180deg); transform:rotate(180deg);"/>
</body>
6、web服务开启小车控制功能:
#!/usr/bin/python3
#coding: utf8
#使用bottle轻量级web服务
from bottle import get,post,run,request,template
from motor import MotorClass
import time
import os
# 保证其他地方调用是路径正确
os.chdir('/home/pi/vehicle/')
motor = MotorClass( )
@get("/")
def index():
return template("index")
####客户端请求,服务器端就发一个index.html 控制界面给客户端
@post("/cmd")
def cmd():
adss = request.body.read().decode() ####接收到客户端发来的数据
print( "web press:" + adss )
vehicle_control(adss) ##传值到主函数 实现对应功能
return "OK"
def vehicle_control( move ):
if move == "front":
motor.forward()
time.sleep (0.5)
elif move == "rear":
motor.reverse()
time.sleep (0.5)
elif move == "left":
motor.left()
time.sleep (0.1)
elif move == "right":
motor.right()
time.sleep (0.1)
motor.stop()
其中控制马达主要代码如下:
#!/usr/bin/python
#coding: utf8
import define as DEF
#使用python的第三方io控制模块
import RPi.GPIO as GPIO
import thread
import time
##############################
#引脚定义
#电机控制引脚定义
GPIO_MOTOR_LEFT_A = 19
GPIO_MOTOR_LEFT_B = 26
GPIO_MOTOR_RIGHT_A = 16
GPIO_MOTOR_RIGHT_B = 20
#舵机控制引脚定义
GPIO_STEER_A = 6
GPIO_STEER_B = 13
class MotorClass:
def __init__(self):
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup( DEF.GPIO_MOTOR_LEFT_A, GPIO.OUT )
GPIO.setup( DEF.GPIO_MOTOR_LEFT_B, GPIO.OUT )
GPIO.setup( DEF.GPIO_MOTOR_RIGHT_A, GPIO.OUT )
GPIO.setup( DEF.GPIO_MOTOR_RIGHT_B, GPIO.OUT )
def __del__(self):
GPIO.cleanup()
# 前进
def forward(self):
GPIO.output( DEF.GPIO_MOTOR_LEFT_A, GPIO.HIGH )
GPIO.output( DEF.GPIO_MOTOR_LEFT_B, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_A, GPIO.HIGH )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_B, GPIO.LOW )
# 后退
def reverse(self):
GPIO.output( DEF.GPIO_MOTOR_LEFT_A, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_LEFT_B, GPIO.HIGH )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_A, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_B, GPIO.HIGH )
# 原地左转
def left(self):
GPIO.output( DEF.GPIO_MOTOR_LEFT_A, GPIO.HIGH )
GPIO.output( DEF.GPIO_MOTOR_LEFT_B, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_A, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_B, GPIO.HIGH )
# 原地右转
def right(self):
GPIO.output( DEF.GPIO_MOTOR_LEFT_A, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_LEFT_B, GPIO.HIGH )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_A, GPIO.HIGH )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_B, GPIO.LOW )
# 停止
def stop(self):
GPIO.output( DEF.GPIO_MOTOR_LEFT_A, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_LEFT_B, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_A, GPIO.LOW )
GPIO.output( DEF.GPIO_MOTOR_RIGHT_B, GPIO.LOW )