web.py服务端,jquery ajax简单例子

来源:互联网 发布:解压软件怎么安装 编辑:程序博客网 时间:2024/06/09 14:07
  1. 在服务端设置好url映射后编写应对客户端的ajax post请求(新手整理思路记录用,若有错误还请指出~

class AjaxFriendReq:    def POST(self):        try:            i = web.input()            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"
不需考虑具体逻辑,web.input()可以获取请求页面的数据集,使用安全的get("string")方法可以获取指定数据。若逻辑符合,操作数据库并返回相应提示用字符串(成功或失败)
<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>
该js在页面加载完毕后执行,为id为frireqbutton的元素添加鼠标点击函数,对服务器发送ajax post请求,url目标为“/ajaxfriendreq”。

dataType设为html,服务器返回时转换成html(若不指定默认为xmld。例子中对应字符串在客户端被转换成html。

data中设置发送请求时从客户端发出的数据。

success:function(msg)中设置服务器请求成功后的逻辑,msg为服务器返回的数据。

此外,在jquery逻辑中,使用$("#tar").html(tarhtmlobj.responseText);可以将ID为tar的元素改变为html格式的服务器返回内容

0 0
原创粉丝点击