---
title: "python笔记（6）——tornado&ajax"
author: "mywebcode"
date: "2013-12-29T04:35:00Z"
tags: []
slug: "python-6-tornado-ajax"
draft: false
lastmod: "2014-04-30T09:04:20Z"
id: 2057478
url: "https://mywebcode.iteye.com/blog/2057478"
---

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")
```