2016-02-27 123 views
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获取用户输入?

回答

1

websocket消息不是新的HTTP请求。 self.request(和像self.get_argument()这样的相关方法)指的是打开websocket并且在新消息到达时不会改变的HTTP请求。相反,您使用websocket消息获取的唯一信息是on_message()的message参数。这包含由JavaScript发送的数据,并且您必须自己解析它。

def on_message(self, message): 
    args = {} 
    tornado.httputil.parse_body_arguments("application/x-www-form-urlencoded", message, args, {}) 
    print(args["nom"][0]) 

你可能想用JSON代替表单编码;当您不需要向后兼容纯HTML表单提交时,通常更容易使用。

+0

啊!谢谢你,Ben,那种工作就像一个魅力,事实上,我发现你在关于'get/post'的文档中发出的通知,但dident在使用websocket时知道如何传递参数。 – Abdelouahab

+0

你为什么用空字典? (它在parse_body_arguments中可用两次) – Abdelouahab

+1

请参阅parse_body_arguments的文档。它需要两个词并填充它们。第一个用于参数,第二个用于文件。你不会在这里发送任何文件,所以我只是通过一个空的丢弃字典,但args字典绑定到本地变量。 –