抱歉各位,也许以前已经有人问过这个问题了。但我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/