一种跨域技术: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+php:php来自不同源的站点

<button class="btn"></button>
//JS
    $(document).ready(function() {
        $(".btn").click(function() {
            $.ajax({type: "GET",
                crossDomain : true,
                url: "http://120.77.34.254/test/test.php",
                dataType: "jsonp",
                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请求
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值