S14_09_JSONP
JSONP
# pip3 install requests
import requests
request.get('http://www.baidu.com')
request.post('http://www.baidu.com')
# 由于浏览器具有同源策略会阻止Ajax请求
# 但不阻止<script src='...'></script>)
# 巧妙:
- 创建script标签
- src=远程地址
- 返回的数据必须是js格式
# 只能发GET请求
# 提供接口:
def jsonp(request):
func = request.GET.get('callback')
content = '%s(1000000)' % (func,)
return HttpResponse(content)
# jQuery请求:
$.ajax({
url: 'http://www.jxntv.cn/data/jmd-jxtv2.html',
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'list'
})
# 参考:
python s12 day13 JavaScript、Dom和jQuery
https://www.cnblogs.com/wupeiqi/articles/5369773.html
# CORS:
跨站资源共享
返回数据设置响应头
参考资料:
Ajax全套 cors
https://www.cnblogs.com/wupeiqi/articles/5703697.html
# 代码:
# view.py
def req(request):
response = requests.get('http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301')
#print(response.content) # 字节
response.encoding = 'utf-8'
#print(response.text) # 字符串
return render(request, 'req.html',{'result': response.text})
# req.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<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://wupeiqi.com:8001/jsonp.html?k1=v1&k2=v2');
xhr.onreadystatechange = function(){
console.log(xhr.responseText);
};
xhr.send();
*/
/*
var tag = document.createElement('script');
tag.src = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403';
document.head.appendChild(tag);
document.head.removeChild(tag);
*/
$.ajax({
url: 'http://www.jxntv.cn/data/jmd-jxtv2.html',
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'list'
})
}
function list(arg){
console.log(arg);
}
</script>
</body>
</html>