如何将信息从客户端发送到服务器?我有点需要通过单击按钮将一些数据从客户端发送到服务器。基本上,我有一个页面,其中有几个按钮,我想尝试在按下时将有关每个按钮的信息(以及有关客户端状态的一些额外信息,但这不是完全必要的)。然后,服务器应处理该信息,并将处理后的版本发送到所有连接的客户端。
客户端不刷新至关重要,因为那样我们将丢失 javascript 游戏引擎中的数据,用户将不得不重新开始。
阿贾克斯合适吗?如果是,有人可以包含一个简短的通用示例,其中包含javascript(客户端)和Flask(服务器端)函数/代码吗?
开箱即用,你不能将持久请求或websockets与Flask之类的东西一起使用。但是,您不一定需要这个 - 您可以将 AJAX 与简单的轮询机制一起使用。
客户端:
$('button').click(function() {
var state = $(this).attr('data-state');
$.post('/clients/', { state: state });
});
// Check for messages every 1 second
var checkDelay = 1000;
var lastMessageSeen = new Date().getTime();
setInterval(function() {
$.get('/clients/', function(result) {
if(result.ready and result.timestamp > lastMessageSeen) {
lastMessageSeen = result.timestamp;
console.log('Message received: ' + result.msg);
}
});
}, checkDelay);
服务器端:
from flask import request, jsonify
@app.route('/clients/', methods=['POST'])
def client_broadcast():
state = request.form['state']
# here you can store the message under a key in Memcached, Redis or another in-memory cache server
store_in_cache(state)
return jsonify(stored=True)
@app.route('/clients/', methods=['GET'])
def client_retrieve():
# retrieve messages from cache
msg, timestamp = retrieve_from_cache()
if msg:
return jsonify(ready=True, msg=msg, timestamp=timestamp)
else:
return jsonify(ready=False)
我省略了store_in_cache
和retrieve_from_cache
函数,因为它取决于您如何处理这些消息。它们是所有浏览器客户端的全局吗?是否要有一个消息队列?