码迷,mamicode.com
首页 > Web开发 > 详细

JSONP

时间:2019-06-08 15:14:14      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:console   浏览器   type   cal   end   llb   cti   需要   function   

JSONP(JSON with Padding) 是 JSON 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。

JSONP本质

由于浏览器的同源策略,会阻止Ajax请求,但是不会阻止<script src=""></script>,因此就可以通过<script src=""></script>的方式发送请求。

注意:JSONP只能发送GET请求

JSONP数据格式

为了配合通过<script>发送请求,服务器端返回的数据应为JSONP格式:

callbackFunction(数据)

因为通过<script src=""></script>发送请求就等于将服务器返回的数据直接放入了<script></script>代码块中,所以服务器需要返回JS格式的数据,一般返回一个回调函数,然后将要发送给浏览器的数据当作参数传给函数,并且浏览器需要先定义一个函数供服务器调用。

示例:

.html:

<body>
<input type="button" id="get-JSONP" value="get" />
</body>
<script src="/static/jQuery3.4.1.js"></script>
<script src="/static/get_jsonp.js"></script>

get_jsonp.js:

$('#get-JSONP').click(function () {
    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);
});

function list(arg){
    console.log(arg);
}

通过这个示例就可以清晰地看出JSONP的原理

通过jQuery发送请求

示例

get_jsonp.js:

$('#u-get').click(function () {
    $.ajax({
        url: 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403',
        type: 'GET',
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback: 'list'
    })
function list(arg){
    console.log(arg);
}

请求类型可以使用POST,但是其实内部仍然将POST转换为GET

JSONP

标签:console   浏览器   type   cal   end   llb   cti   需要   function   

原文地址:https://www.cnblogs.com/dbf-/p/10990452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!