<p>数据位于<code>self.request.arguments</code>。此外,还需要向客户端返回有效的json。在</p>
<pre><code>class AjaxHandler(tornado.web.RequestHandler):
def post(self):
my_data = self.request.arguments['test_data']
# do something with my_data
self.write(json.dumps({'status': 'ok'}))
self.finish()
</code></pre>
<p>处理程序的<code>self.write(json.dumps({'status': 'ok'}))</code>响应对于完成与客户机的事务是必需的:任何有效的json都可以;内容是什么并不重要。(如果客户机似乎没有取回json,请参阅<a href="https://stackoverflow.com/a/26739478/1599229">this answer</a>。)</p>
<p>也可能是<code>_xsrf_cookies: True</code>在你的<code>settings</code>内<code>run_server.py</code>。如果是这样,<code>ajax</code>请求本身将被Tornado阻止(您将在控制台上看到<code>400 Bad Request</code>)。在</p>
<p>为了解决这个问题,<code>XSRF</code>令牌可能。。。通过名为<code>HTTP</code>的<code>HTTP</code>头传递,<a href="http://tornado.readthedocs.org/en/latest/guide/security.html" rel="nofollow noreferrer">doc</a>表示。通过<code>get</code>的页面包含或调用<code>ajax</code>逻辑的<code>get</code>设置cookie。医生说,这样做“足以将cookie设置为副作用”:</p>
^{pr2}$
<p>然后可以在客户机中获取cookie(这里通过jQuery<a href="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js" rel="nofollow noreferrer">$.cookie plugin</a>):</p>
<pre><code>var token = $.cookie('_xsrf');
</code></pre>
<p>在调用中嵌入标记作为自定义<code>headers</code>参数:</p>
<pre><code>$.ajax({
url: '/task',
headers: {'X-XSRFToken' : token },
data: {'test_string': 'test success'},
dataType: "JSON",
type: "POST",
success: function ( data , status_text, jqXHR) {
alert('ajax success')
},
error: function ( data , status_text, jqXHR ) {
alert('ajax fail')
},
});
</code></pre>
<p>或者,也可以将其作为<code>data</code>中的一个字段。(如果您要<code>ajax</code>将一个JavaScript对象作为一个字段,那么为了在服务器端获得一个结构良好的<code>dict</code>,您应该</strong><code>JSON.stringify</code>它):</p>
<pre><code>var packet = {"_xsrf": $.cookie("_xsrf"), "test_string": "test success", "js_obj": JSON.stringify(js_obj)};
$.ajax({
url: '/task',
data: packet,
dataType: "JSON",
type: "POST",
success: function ( data , status_text, jqXHR) {
alert('ajax success')
},
error: function ( data , status_text, jqXHR ) {
alert('ajax fail')
},
});
</code></pre>
<p>还有一个在<a href="http://tornado.readthedocs.org/en/latest/guide/structure.html" rel="nofollow noreferrer">doc</a>中引用的<a href="https://github.com/tornadoweb/tornado/blob/stable/demos/chat/static/chat.js" rel="nofollow noreferrer">sample chat app</a>中管理<code>_xsrf_cookies</code>的示例。在</p>