jsonp实现跨域ajax,基本原理是利用scrip的src可以跨域,需要客户端和服务器端同时配合,
一、基本原理和流程
(一)客户端
1、自动生成script标签,
2、并将ajax的目标地址url,设置为新建script标签的src,
3、将新建标签插入head标签,自动执行,
4、执行完毕,删除新建标签,
5、自定义回调函数,获取ajax请求返回的数据,并进行应用,

#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class IndexHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') def post(self, *args, **kwargs): self.write('t1.post') # 路径解析 settings = { "template_path":"views", "static_path":"statics", "static_url_prefix":"/sss/", } # 二级路由,先匹配域名, application = tornado.web.Application([ (r"/index",IndexHandler), ],**settings) # 开启服务器,监听 if __name__ == "__main__": application.listen(8001) tornado.ioloop.IOLoop.instance().start()

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <input type="button" value="ajax" onclick="JsonpAjax();" /> <!--<script src="sss/jquery-1.12.4.min.js"></script>--> <script> <!--利用scrip标签的src实现跨域--> function JsonpAjax(){ var tag = document.createElement('script'); <!--创建一个script标签--> tag.src = 'http://ajax2.com:8888/index'; <!--通过script标签的src进行跨域--> document.head.appendChild(tag); <!--将新建标签添加到head标签中自动执行--> document.head.removeChild(tag); <!--执行完成,将新建标签删除--> }; <!--利用回调函数,获取ajax请求的返回数据,并应用--> function JsonpCallBack(arg){ console.log(arg); }; </script> </body> </html>
(二)服务器端
服务器端的返回值,需要将返回数据包裹在指定的回调函数内,

#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class IndexHandler(tornado.web.RequestHandler): def get(self): self.write('JsonpCallBack("t2-get")') # 路径解析 settings = { "template_path":"views", "static_path":"statics", "static_url_prefix":"/sss/", } # 二级路由,先匹配域名, application = tornado.web.Application([ (r"/index",IndexHandler), ],**settings) # 开启服务器,监听 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
二、指定回调函数时
(一)客户端
1、url访问地址中,携带指定回调函数名称的参数
(二)服务器端
1、返回数据前,先获取回调函数的名称,进行组合,