JSONP
JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题。由于同源策略,一般来说位于 server1.example.com 的网页无法与不是 server1.example.com的服务器沟通,而 HTML 的<script> 元素是一个例外。利用 <script> 元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP。用 JSONP 抓到的资料并不是 JSON,而是任意的JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析。
原理:
- 创建script标签
- src=远程地址
- 返回的数据必须是js格式
-
只能发GET请求
1、什么是同源策略?
处理文件:
import requests
def jsonp(request):
# 获取url信息
response = requests.get('http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301')
response.encoding = 'utf-8' # 进行编码
return render(request,'jsonp.html',{'result':response.text}) # response.text 请求内容
HTML文件:
<body>
<h1>后台获取的结果</h1>
{{ result }}
<h1>js直接获取结果</h1>
<input type="button" value="获取数据" onclick="getContent();" />
<div id="container"></div>
<script src="/static/jquery-1.8.2.js"></script>
<script>
function getContent() {
var xhr = new XMLHttpRequest(); // 创建对象
xhr.open('GET', 'http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301'); // GET方式打开
xhr.onreadystatechange = function () { // 收到返回值时执行
console.log(xhr.responseText);
};
xhr.send() // 发送
}
</script>
</body>
注:点击js直接获取结果时,浏览器显示下面报错信息,由于浏览器只接受http://127.0.0.1:8000发过来的信息,对于天气网站发过来的信息直接屏蔽掉了,这就是同源策略,那有没有什么方式可以解决?
XMLHttpRequest cannot load http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access.
2、巧用script标签src属性
script标签不受同源策略的影响
处理文件:
import requests
def jsonp(request):
# 获取url信息
response = requests.get('http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301')
response.encoding = 'utf-8' # 进行编码
return render(request,'jsonp.html',{'result':response.text}) # response.text 请求内容
def jsonp_api(request):
return HttpResponse('alert(123)')
HTML文件:
<body>
<h1>后台获取的结果</h1>
{{ result }}
<h1>js直接获取结果</h1>
<input type="button" value="获取数据" onclick="getContent();" />
<div id="container"></div>
<script>
function getContent() {
var tag = document.createElement('script');
tag.src = '/jsonp_api.html';
document.head.appendChild(tag);
// document.head.removeChild(tag);
}
</script>
</body>
注:js请求时为了方便,还是请求的是当前程序url;执行完上面代码会发现一个神奇的状况,页面会弹出123信息,表明script获取信息成功
3、对前后端稍加改造,使用方法更加动态化
处理文件:
def jsonp(request):
return render(request,'jsonp.html') # response.text 请求内容
def jsonp_api(request):
func = request.GET.get('callback') # 获取用户callback参数
content = '%s(10000)'%func # 执行func(10000)函数
return HttpResponse(content)
HTML文件:
<body>
<h1>后台获取的结果</h1>
{{ result }}
<h1>js直接获取结果</h1>
<input type="button" value="获取数据" onclick="getContent();" />
<div id="container"></div>
<script>
function getContent() {
var tag = document.createElement('script');
tag.src = '/jsonp_api.html?callback=list'; // 自定义callback参数,与后台达成默契
document.head.appendChild(tag);
// document.head.removeChild(tag);
}
function list(arg){ // 自定义函数与callback=list相对应
alert(arg);
}
</script>
</body>
注:js发请求时,带上callback参数,然后定义参数对应的方法,后台会把数据传入此方法内并且执行执行;至于要打印还是弹框,就看用户自己的需求去处理了;jsonp的原理和实现过程就是上述代码的实现
4、实例应用+ajax
处理文件:
import requests
def jsonp(request):
response = requests.get('http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403')
response.encoding = 'utf-8' # 进行编码
return render(request, 'jsonp.html', {'result': response.text}) # response.text 请求内容
HTML文件:
<body>
<h1>后台获取的结果</h1>
{{ result }}
<h1>js直接获取结果</h1>
<input type="button" value="获取数据" onclick="getContent();" />
<div id="container"></div>
<script src="/static/jquery-1.8.2.js"></script>
<script>
function getContent() {
$.ajax({
url: 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403',
type: 'POST',
dataType: 'jsonp', // 即使写的type是POST也是按照GET请求发送
jsonp: 'callback',
jsonpCallback: 'list'
});
}
function list(arg){ // 自定义函数与callback=list相对应
console.log(arg);
var data = arg['data'];
for(k in data){
var tr = document.createElement('td');
var week = data[k]['week'];
var list = data[k]['list'];
tr.textContent =week
document.body.appendChild(tr);
console.log(week);
for(i in list){
var name = list[i]['name'];
console.log(name)
}}}
</script>
</body>
网站获取到的数据
list({data:[ { "week":"周日", "list":[ { "time":"0030", "name":"通宵剧场六集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0530", "name":"《都市现场》60分钟精编版(重播)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0630", "name":"《快乐生活一点通》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0700", "name":"《e早晨报》60分钟直播版块", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0800", "name":"精选剧场四集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1120", "name":"《地宝当家》(重播)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1200", "name":"《都市60分》60分钟直播版块", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1300", "name":"《谁是赢家》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1400", "name":"女性剧场三集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1700", "name":"《快乐生活一点通》精编版", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1730", "name":"《地宝当家》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1800", "name":"《都市现场》90分钟直播版块", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1930", "name":"《都市情缘》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2000", "name":"《晚间800》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2020", "name":"《都市剧场》黄金剧(第1集)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2110", "name":"《都市剧场》黄金剧(第2集)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2200", "name":"《拍案》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2230", "name":"江西新闻联播(重播)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2250", "name":"都市晚剧场", "link":"http://www.jxntv.cn/live/jxtv2.shtml" } ] }, { "week":"周一", "list":[ { "time":"0030", "name":"通宵剧场六集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0530", "name":"《都市现场》60分钟精编版(重播)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0630", "name":"《快乐生活一点通》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0700", "name":"《e早晨报》60分钟直播版块", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"0800", "name":"精选剧场四集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1120", "name":"《地宝当家》(重播)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1200", "name":"《都市60分》60分钟直播版块", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1300", "name":"《谁是赢家》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1400", "name":"女性剧场三集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1700", "name":"《快乐生活一点通》精编版", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1730", "name":"《地宝当家》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1800", "name":"《都市现场》90分钟直播版块", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"1930", "name":"《都市情缘》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2000", "name":"《晚间800》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2020", "name":"《都市剧场》黄金剧(第1集)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2110", "name":"《都市剧场》黄金剧(第2集)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2200", "name":"《拍案》", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2230", "name":"江西新闻联播(重播)", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":"2250", "name":"都市晚剧场", "link":"http://www.jxntv.cn/live/jxtv2.shtml" } ] },{ "week":"周二", "list":[ { "time":"0030", "name":"通宵剧场六集连播", "link":"http://www.jxntv.cn/live/jxtv2.shtml" }, { "time":