对不起,伙计们,也许以前有人问过这个问题。但是我google了几天,仍然无法解决问题。我正在使用带有 Python 的 Google App Engine 开发一个聊天系统。我希望用户输入她/他的消息并单击“提交”按钮。该操作将触发 Ajax 发布函数“addMsg()”将消息发布到 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>
消息.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.