python - python Ajax如何发布数据

标签 python ajax google-app-engine

抱歉各位,也许以前已经有人问过这个问题了。但我google了好几天还是没能解决这个问题。我正在使用 Google App Engine 和 Python 开发一个聊天系统。我希望用户输入她/他的消息并单击“提交”按钮。该操作将触发 Ajax post 函数“addMsg()”将消息 POST 到 Chat 类(URL:“/chat”),这会将消息添加到数据存储区。还有另一个 Ajax 函数“updateMsg()”,它将定期更新消息列表。

该代码对于消息更新工作正常,但是,我无法正确发布消息。有谁能够帮助我?谢谢。这是我的代码:

聊天.html:

    <p>
    <form method="" action="">
    <input type="text" name="message" size="60" /><br />
    <input type="button" value="Submit" onclick="addMsg('message')" />
    </form>
    </p>
    <div id="chatcontent"> </div>
    <script>
    function addMsg(message) {
        $.ajax({
            type: "POST",
            url: "/chat",
            data: {'message': message},
            cache: false
        });
    }
    </script>

    <script>
    $(document).ready(function() {
        function updateMsg() {
            $.ajax({
               url: "/message",
               cache: false,
               success: function(returndata){
                    $("#chatcontent").html(returndata);
               }
            });
            setTimeout(updateMsg, 4000);
        }
        updateMsg();
    });
    </script>

message.html:

    {% for chat in chatlist %}
    <p>
      {{ chat.text }} ({{ chat.user.account }}) {{chat.created|date:"D d M Y" }}
    </p>
    {% endfor %}

聊天.py:

    # Called by URL "/chat"
    class Chat(webapp2.RequestHandler):
        def post(self):
            message = self.request.get('message')
            newchat = ChatMessage(user=self.session['userkey'], text=message, created=datetime.datetime.now())
    newchat.put()

    # Called by URL "/message"
    class Message(webapp2.RequestHandler):
        def get(self):
            que = db.Query(ChatMessage).order('-created')
            chatlist = que.fetch(limit=100)
            render(self, 'message.html', {'chatlist': chatlist})
            # Note: render() is a function to be imported, which is just a normal template rendering function. It works fine and is omitted here.

最佳答案

聊天.html

<p>
<input type="text" name="message" size="60" /><br />
<input type="button" value="Submit" onclick="addMsg()" />
</p>
<div id="chatcontent"> </div>
<script>
function addMsg() {
    var message = $('input[name=message]').val();
    $.ajax({
        type: "POST",
        url: "/chat",
        data: {'message': message},
        cache: false
    });
}
</script>

关于python - python Ajax如何发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13262824/

相关文章:

python - 如何根据行过滤

python - Pandas 按多列 NULL 过滤

python - 将符号转换为 HTML 实体

javascript - 通过ajax获取json数据

jquery - 如何在验证事件上显示弹出窗口?

python - 在python中查找日期列表之间的差异

php - 如何制作一个多语言的 php 站点?

google-app-engine - 在 Google Compute Engine 中访问任务队列和 Google Datastore

java - 使用 Maven EAR 打包的 GWT 应用程序运行 SuperDevMode

java - 了解执行 Google Datastore 查询时的 "CancellationException: Task was cancelled"错误