def jsonp(request): ???#JSONP存在的原因是浏览器具有同源(域名)策略 (浏览器阻止Ajax,但是无法阻止<script src=‘..‘></script>) ???#奇招: ????????#创建script标签 ????????#src=远程地址 ????????#返回的数据必须是js格式 ????????#jsonp只能发GET请求 ???response=requests.get(‘http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301‘) ???print(response.content) ???response.encoding=‘utf-8‘ ???return render(request,‘jsonp.html‘,{‘result‘:response.text})def jsonpp(request): ???print(request.GET) ???ret =‘‘‘callback(123)‘‘‘ ???return HttpResponse(ret)
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body><h1>后台获取结果</h1>{{ result }}<h1>js直接获取结果</h1><input type="button" value="获取数据" onclick="getContent();"><div id="content"></div><script src="/static/jquery-1.12.4.js"></script><script> ???function getContent() { ???????{# ???var xhr = new XMLHttpRequest();#} ???????{# ???xhr.open(‘GET‘,‘http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301‘);#} ???????{# ???xhr.onreadystatechange=function(){#} ???????{# ???????console.log(xhr.responseText);#} ???????{# ???}#} ???????{# ???xhr.send();#} ???????{# ???????var tag=document.createElement(‘script‘);#} ???????{# ???????tag.src=‘http://127.0.0.1/jsonpp/?k1=v1&k2=v2‘;#} ???????{# ???????document.head.appendChild(tag);#} ???????{# ???????document.head.remove(tag);#} ???????{##} ???????{##} ???????{# ???}#} ???????{##} ???????//ajax方式 ???????$.ajax({ ???????????url:‘http://www.jxntv.cn/data/jmd-jxtv2.html‘, ???????????type:‘POST‘, ???????????dataType:‘jsonp‘, ???????????jsonp:‘callback‘, ???????????jsonCallback:‘list‘ ???????}) ???} ??????????function list(arg) { ???????????????console.log(arg); ???????????}</script></body></html>
JSONP
原文地址:https://www.cnblogs.com/sunhao96/p/9040982.html