JSON with padding 是一种数据交换的技巧,用于解决主流浏览器的跨域数据访问的问题!
因为同源策略,通常来讲位于A服务器的网页是没法与其余服务器上的资源沟通的 而html中的`<script>`是一个特例,JSONP就是利用`<script>`这个标签实例动态地 从其余服务器获取资源(通常来讲是一些文本内容)。
客户端JS代码首先定义一个回调函数,该回调函数接收将要被处理的数据参数,参数个数不定。javascript
客户端HTML代码嵌入一段<script>
引用,src
指向服务器程序的URL,并在URL在给定一个参数,它的值就是上面1定义的function名php
服务器端代码(如PHP)接收到请求,解析参数取得客户端中定义的回调函数名,并将取得的回调函数名看成函数名称与数据合并输出一段 JS调用函数的代码html
<?php $func = $_GET['callback']; //这里获取客户JS定义的回调函数名称 $data = 'This is the jsonp data on crossdomain request'; echo "$func('{$data}')"; //这是一段JS代码
<!DOCTYPE html> <html> <head> <title>Json test</title> </head> <body> <h1 id="padding-content"></h1> <a href="javascript:;" class="button">json data</a> </body> <script type="text/javascript"> function callbackfunc(data){ $("#padding-content").text("callback:"+data); } </script> <script type="text/javascript" src="http://www.B.com/jsonp.php?callback=callbackfunc"></script> </html>
callback:This is the jsonp data on crossdomain request
<!DOCTYPE html> <html> <head> <title>Json test</title> <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> </head> <body> <h1 id="padding-content"></h1> <a href="javascript:;" class="button">json data</a> </body> <script type="text/javascript"> $(".button").click(function(){ $.ajax({ url:"http://www.B.com/jsonp.php", dataType:"jsonp", type:"get", jsonpCallback:"testJsonpCallBackFunc", error:function(err, errstr){ $("#padding-content").text(errstr); }, success:function(resp){ $("#padding-content").text(resp); } }); }); </script> </html>
callback:This is the jsonp data on crossdomain request
java