您的位置:首页 > 编程语言 > Python开发

python笔记(6)——tornado&ajax

2013-12-29 04:35 417 查看
tornado与ajax并用,ajax用于实现前台与后台的交互。实现了一个小小的demo,应该是可以的:

$("#submitComment").click(function() {
var comment = encodeURI(encodeURI($("#comment").val()));
if(comment == "") {
alert("please input your comment!");
}

$.ajax({
type: 'POST',
url: 'http://localhost:8000/twitter/'+"{{name}}",
data: {"comment" : comment},

success: function(data) {
if(data == "1") {
showComment(comment);
}else {
alert("fail comment!");
}
}
});
});下面用$.ajax向后台传数据,success函数用于定义成功后的操作。要实现的效果是微博的无刷新评论,我的思路是将数据传到后台后,后台将数据存入数据库,若成功则返回‘1’,若不成功,则返回‘0’;ajax里面的success函数检测到后台返回的这个数据,选择是否进行评论的展示。
后台部分代码如下:

def post(self, name):
name = tornado.escape.xhtml_escape(self.current_user)

msg = self.get_argument("comment")
temp = {"auther": name, "time": "Nov 26 2013 10:30:00", "content": msg}

conn = pymongo.Connection("localhost", 27017)
db = conn.twitterDB
userSets = db.userSets

if msg is not None:
doc = userSets.find_one({"name": name})
doc['twitters'].insert(0, temp)
userSets.save(doc)
self.write("1")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python ajax tornado post 微博