0
我尝试从用户获取数据:为什么request.body是空的?
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
nom = self.get_argument("nom") # this will return an error, because nom is not found
# I then tried to retrieve the result of the body,
print(self.request.body) # nothing to show!
def on_close(self):
print("WebSocket closed")
客户端:
$(document).ready(function() {
$("#frm").on("submit", function(e){
var formdata = $("#frm").serialize()
console.log(formdata) // gives _xsrf=2%7C0fc414f0%7Cf5e0bd645c867be5879aa239b5ce0dfe%7C1456505450&nom=sdfsdf
var ws = new WebSocket("ws://localhost:8000/websocket");
ws.onopen = function() {
ws.send(formdata);
};
ws.onmessage = function (evt) {
alert(evt.data);
};
e.preventDefault();
})
})
</script>
<form action="/websocket" method="post" id="frm">
{% raw xsrf_form_html() %}
<input type="text" name="nom" autofocus>
<button class="ui primary button">Envoyer</button>
</form>
我已经尝试了简单的Ajax方法,并得到了:
class AjaxHandler(tornado.web.RequestHandler):
def post(self):
print self.request.body
#gives: _xsrf=2%7C0d466237%7Cf762cba35e040d228518d4feb74c7b39%7C1456505450&nom=hello+there
我的问题:如何使用websocket获取用户输入?
啊!谢谢你,Ben,那种工作就像一个魅力,事实上,我发现你在关于'get/post'的文档中发出的通知,但dident在使用websocket时知道如何传递参数。 – Abdelouahab
你为什么用空字典? (它在parse_body_arguments中可用两次) – Abdelouahab
请参阅parse_body_arguments的文档。它需要两个词并填充它们。第一个用于参数,第二个用于文件。你不会在这里发送任何文件,所以我只是通过一个空的丢弃字典,但args字典绑定到本地变量。 –