微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

一种跨域技术:JSONP

跨域技术是前端面试中常见话题。JSONP就是一种跨域技术
我撰写此文是为了加深对JSONP的印象

何为跨域?

A resource makes a cross-origin HTTP request when it requests a resource from a domain or port 
which is different from the one which the first resource itself serves. 
For example,an HTML page served from http://domain-a.com makes an <img> src request for 
http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets,images and 
scripts from separate domains.
译文:浏览器请求与当前域或者窗口不同的域或窗口。这种请求被称为被称为跨域请求。
请求CSS样式表,JS脚本也在此列,这在互联网是很常见的。

为什么要有专门支持跨域的技术?

因为浏览器遵循同源策略,严格限制跨域。何为同源,即协议、域名、端口相同。

有了跨域技术支持,就可以访问任意站点的任意资源了吗?

不是,需要被跨域的网站支持

什么是JSONP?

下面这段话来自<JS高程>,JSONP是JSON with padding的简写,是应用JSON的新方法。
JSONP看起来与JSON差不多,只不过是包含在里函数调用中的JSON。举个栗子,同样的内容:JSON返回的是:
{"name":"achao"}
JSONP返回的是
callbackFuncName({"name":"achao"})
callbackFuncName是浏览器传递过去的回调函数名,是自定义的。

JSONP请求:

function handleResponse(response) {
    console.log(response);
}
var script=document.createElement("script");
script.src="http://freegeoip.net/json/?callback=handleResponse";
document.body.insertBefore(script,document.body.firstChild);
http://freegeoip.net/json/ 这个站点提供了JSONP服务,console.log是你主机的地理信息:
city:"Hangzhou"
country_code:"CN"
country_name:"China"
ip:"183.157.160.24"
latitude:30.2936
longitude:120.1614
metro_code:0
region_code:"33"
region_name:"Zhejiang"
time_zone:"Asia/Shanghai"
zip_code:""

JSONP的ajax支持

<!--html-->
<button class="btn"></button>
//JS
$(document).ready(function() {
        $(".btn").click(function() {
            $.ajax({type: "GET",crossDomain : true,url: "http://freegeoip.net/json/",dataType: "jsonp",jsonp: "jsonp",jsonpCallback: "myJsonMethod"
            });
        });
    });
    function myJsonMethod(response){
        console.log (response);
    }

response:

myJsonMethod({"ip":"183.157.160.24","country_code":"CN","country_name":"China","region_code":"33","region_name":"Zhejiang","city":"Hangzhou","zip_code":"","time_zone":"Asia/Shanghai","latitude":30.2936,"longitude":120.1614,"metro_code":0});

ajax+PHPPHP来自不同源的站点

<button class="btn"></button>
//JS
    $(document).ready(function() {
        $(".btn").click(function() {
            $.ajax({type: "GET",url: "http://120.77.34.254/test/test.PHP",jsonpCallback: "myJsonMethod"
            });
        });
    });
    function myJsonMethod(response){
        console.log (response);
    }
//PHP

<?PHP header('content-type: application/json; charset=utf-8');
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['callback'] . '('.json_encode($data).')';

response:

myJsonMethod({"a":1,"b":2,"c":3,"d":4,"e":5})

JSONP的优缺点(这个在面试会问到)

优点:
a)支持老式浏览器

关于支持老式浏览器:https://stackoverflow.com/questions/12296910/so-jsonp-or-cors

缺点:
a)JSONP是从其他域中加载代码执行,如果其他域不安全,在响应中夹带一些恶意代码,此时只能放弃JSONP
b)要确定JSONP请求是否失败并不容易。HTML5给<script>标签增加的onerror事件处理程序没有得到任何浏览器支持。
开发人员不得不使用计时器,但是这并不如任意,因为每个用户上网的速度和带宽不尽相同。
c)只支持get请求

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐