下面介绍使用 tornado 做后端处理 ajax 跨域问题
添加响应头
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
print "setting headers!!!"
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
def post(self):
self.write('some post')
def get(self):
self.write('some get')
def options(self):
# no body
self.set_status(204)
self.finish()
客户端 js 示例
1
2
3
4
5
6
7
8
9
10
11
12
$.ajax({
url: "http://some_tornado/api",
type: "POST",
crossDomain: true,
data: 'some_data',
success: function (response) {
alert(response);
},
error: function (xhr, status) {
alert("error");
}
});
本文网址: https://pylist.com/topic/137.html 转摘请注明来源