透彻理解JSONP原理及使用


什么是JSONP

首先提一下JSON这个概念,JSON是一种轻量级的数据传输格式,被广泛应用于当前Web应用中。JSON格式数据的编码和解析基本在所有主流语言中都被实现,所以现在大部分前后端分离的架构都以JSON格式进行数据的传输。

那么JSONP是什么呢?
首先抛出浏览器同源策略这个概念,为了保证用户访问的安全,现代浏览器使用了同源策略,即不允许访问非同源的页面,详细的概念大家可以自行百度。这里大家只要知道,在ajax中,不允许请求非同源的URL就可以了,比如www.a.com下的一个页面,其中的ajax请求是不允许访问www.b.com/c.php这样一个页面的。

JSONP就是用来解决跨域请求问题的,那么具体是怎么实现的呢?

JSONP原理

ajax请求受同源策略影响,不允许进行跨域请求,而script标签src属性中的链接却可以访问跨域的js脚本,利用这个特性,服务端不再返回JSON格式的数据,而是返回一段调用某个函数的js代码,在src中进行了调用,这样实现了跨域。

JSONP具体实现

1.首先看下ajax中如果进行跨域请求会如何。
前端代码在域www.practice.com下面,使用ajax发送了一个跨域的get请求


<html>
<head>
    <title>GoJSONPtitle>
head>
<body>
<script type="text/javascript">
    function jsonhandle(data){
        alert("age:" + data.age + "name:" + data.name);
    }
script>
<script type="text/javascript" src="jquery-1.8.3.min.js">
script>
<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type : "get",
            async: false,
            url : "http://www.practice-zhao.com/student.php?id=1",
            type: "json",
            success : function(data) {
                jsonhandle(data);
            }

        });
    });
script>
body>
html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

后端PHP代码放在域www.practice-zhao.com下,简单的输出一段json格式的数据

jsonhandle({
    "age" : 15,
    "name": "John",
})
  • 1
  • 2
  • 3
  • 4

当访问前端代码http://www.practice.com/gojsonp/index.html 时 chrome报以下错误
这里写图片描述
提示了不同源的URL禁止访问

2.下面使用JSONP,将前端代码中的ajax请求去掉,添加了一个script标签,标签的src指向了另一个域www.practice-zhao.com下的remote.js脚本


<html>
<head>
    <title>GoJSONPtitle>
head>
<body>
<script type="text/javascript">
    function jsonhandle(data){
        alert("age:" + data.age + "name:" + data.name);
    }
script>
<script type="text/javascript" src="jquery-1.8.3.min.js">
script>
<script type="text/javascript" src="http://www.practice-zhao.com/remote.js">script>
body>
html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

这里调用了跨域的remote.js脚本,remote.js代码如下:

jsonhandle({
    "age" : 15,
    "name": "John",
})
  • 1
  • 2
  • 3
  • 4

也就是这段远程的js代码执行了上面定义的函数,弹出了提示框
这里写图片描述

3.将前端代码再进行修改,代码如下:


<html>
<head>
    <title>GoJSONPtitle>
head>
<body>
<script type="text/javascript">
    function jsonhandle(data){
        alert("age:" + data.age + "name:" + data.name);
    }
script>
<script type="text/javascript" src="jquery-1.8.3.min.js">
script>
<script type="text/javascript">
    $(document).ready(function(){
        var url = "http://www.practice-zhao.com/student.php?id=1&callback=jsonhandle";
        var obj = $('
                    
                    

你可能感兴趣的:(ajax,jsonp)