我理解JSON,但不理解JSONP。维基百科关于JSON的文档是JSONP的最高搜索结果。上面写着:

JSONP或“带填充的JSON”是一个JSON扩展,其中前缀被指定为调用本身的输入参数。

嗯?什么电话?这对我来说毫无意义。JSON是一种数据格式。没有电话。

第二个搜索结果来自一个叫雷米的人,他写了关于JSONP的文章:

JSONP是脚本标记注入,将服务器的响应传递给用户指定的函数。

我可以理解,但这仍然没有任何意义。


那么什么是JSONP?为什么创建它(它解决了什么问题)?我为什么要用它?


附录:我刚刚在维基百科上为JSONP创建了一个新页面;根据jvenema的回答,它现在对JSONP有了清晰而透彻的描述。


当前回答

JSONP通过构造一个“脚本”元素(以HTML标记或通过JavaScript插入到DOM中)来工作,该元素请求远程数据服务位置。响应是加载到浏览器的javascript,带有预定义函数的名称以及传递的参数,该参数是请求的JSON数据。当脚本执行时,该函数与JSON数据一起被调用,从而允许请求页面接收和处理数据。

更多阅读请访问:https://blogs.sap.com/2013/07/15/secret-behind-jsonp/

客户端代码段

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <title>AvLabz - CORS : The Secrets Behind JSONP </title>
     <meta charset="UTF-8" />
    </head>
    <body>
      <input type="text" id="username" placeholder="Enter Your Name"/>
      <button type="submit" onclick="sendRequest()"> Send Request to Server </button>
    <script>
    "use strict";
    //Construct the script tag at Runtime
    function requestServerCall(url) {
      var head = document.head;
      var script = document.createElement("script");

      script.setAttribute("src", url);
      head.appendChild(script);
      head.removeChild(script);
    }

    //Predefined callback function    
    function jsonpCallback(data) {
      alert(data.message); // Response data from the server
    }

    //Reference to the input field
    var username = document.getElementById("username");

    //Send Request to Server
    function sendRequest() {
      // Edit with your Web Service URL
      requestServerCall("http://localhost/PHP_Series/CORS/myService.php?callback=jsonpCallback&message="+username.value+"");
    }    

  </script>
   </body>
   </html>

服务器端PHP代码

<?php
    header("Content-Type: application/javascript");
    $callback = $_GET["callback"];
    $message = $_GET["message"]." you got a response from server yipeee!!!";
    $jsonResponse = "{\"message\":\"" . $message . "\"}";
    echo $callback . "(" . $jsonResponse . ")";
?>

其他回答

JSONP通过构造一个“脚本”元素(以HTML标记或通过JavaScript插入到DOM中)来工作,该元素请求远程数据服务位置。响应是加载到浏览器的javascript,带有预定义函数的名称以及传递的参数,该参数是请求的JSON数据。当脚本执行时,该函数与JSON数据一起被调用,从而允许请求页面接收和处理数据。

更多阅读请访问:https://blogs.sap.com/2013/07/15/secret-behind-jsonp/

客户端代码段

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <title>AvLabz - CORS : The Secrets Behind JSONP </title>
     <meta charset="UTF-8" />
    </head>
    <body>
      <input type="text" id="username" placeholder="Enter Your Name"/>
      <button type="submit" onclick="sendRequest()"> Send Request to Server </button>
    <script>
    "use strict";
    //Construct the script tag at Runtime
    function requestServerCall(url) {
      var head = document.head;
      var script = document.createElement("script");

      script.setAttribute("src", url);
      head.appendChild(script);
      head.removeChild(script);
    }

    //Predefined callback function    
    function jsonpCallback(data) {
      alert(data.message); // Response data from the server
    }

    //Reference to the input field
    var username = document.getElementById("username");

    //Send Request to Server
    function sendRequest() {
      // Edit with your Web Service URL
      requestServerCall("http://localhost/PHP_Series/CORS/myService.php?callback=jsonpCallback&message="+username.value+"");
    }    

  </script>
   </body>
   </html>

服务器端PHP代码

<?php
    header("Content-Type: application/javascript");
    $callback = $_GET["callback"];
    $message = $_GET["message"]." you got a response from server yipeee!!!";
    $jsonResponse = "{\"message\":\"" . $message . "\"}";
    echo $callback . "(" . $jsonResponse . ")";
?>

JSONP代表带填充的JSON。

这是一个网站,有很多例子,从最简单的使用这一技术到最先进的平面JavaScript的解释:

w3schools.com/JSONP

上面描述的我最喜欢的技术之一是Dynamic JSON Result,它允许以URL参数将JSON发送到PHP文件,并让PHP文件根据获得的信息返回JSON对象。

jQuery等工具也有使用JSONP的工具:

jQuery.ajax({
  url: "https://data.acgov.org/resource/k9se-aps6.json?city=Berkeley",
  jsonp: "callbackName",
  dataType: "jsonp"
}).done(
  response => console.log(response)
);

因为您可以要求服务器为返回的JSON对象添加前缀。例如

function_prefix(json_object);

以便浏览器将JSON字符串作为表达式“内联”求值。这一技巧使服务器可以直接在客户端浏览器中“注入”javascript代码,并且绕过“同源”限制。

换句话说,您可以实现跨域数据交换。


通常,XMLHttpRequest不允许直接进行跨域数据交换(需要通过同一域中的服务器),而:

<script src=“some_other_domain/some_data.js&prefix=function_prefix>`可以从不同于源域的域访问数据。


同样值得注意的是:即使在尝试这种“技巧”之前,服务器应该被认为是“可信的”,但对象格式等可能改变的副作用也可以得到控制。如果使用function_prefix(即正确的js函数)接收JSON对象,则所述函数可以在接受/进一步处理返回的数据之前执行检查。

JSONP实际上是克服XMLHttpRequest同域策略的一个简单技巧。(如您所知,不能将AJAX(XMLHttpRequest)请求发送到其他域。)

因此,我们必须使用脚本HTML标记,而不是使用XMLHttpRequest,这些标记通常用于加载js文件,以便js从另一个域获取数据。听起来很奇怪?

事实是,脚本标记可以以类似于XMLHttpRequest的方式使用!看看这个:

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data';

加载数据后,您将得到一个如下所示的脚本段:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

然而,这有点不方便,因为我们必须从脚本标记中获取这个数组。因此,JSONP的创建者决定,这将更好地工作(而且是这样):

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data?callback=my_callback';

注意到那边的my_callback函数了吗?因此,当JSONP服务器收到您的请求并找到回调参数时,它将返回以下内容,而不是返回纯js数组:

my_callback({['some string 1', 'some data', 'whatever data']});

看看利润在哪里:现在我们得到了自动回调(my_callback),一旦我们得到数据,它就会被触发。这就是关于JSONP的所有知识:它是回调和脚本标记。

注意:这些是JSONP用法的简单示例,它们不是可用于生产的脚本。

基本JavaScript示例(使用JSONP的简单Twitter提要)

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>

基本jQuery示例(使用JSONP的简单Twitter提要)

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>

JSONP代表带填充的JSON。(这项技术的名称很差,因为它和大多数人认为的“填充”毫无关系。)

JSONP是解决跨域脚本错误的好方法。您可以使用纯JS的JSONP服务,而无需在服务器端实现AJAX代理。

您可以使用b1t.co服务查看其工作原理。这是一个免费的JSONP服务,让您可以缩小URL。以下是用于服务的url:

http://b1t.co/Site/api/External/MakeUrlWithGet?callback=[resultsCallBack]&url=[escapedUrlToMinify]

例如呼叫,http://b1t.co/Site/api/External/MakeUrlWithGet?callback=whateverJavascriptName&url=google.com

将返回

whateverJavascriptName({"success":true,"url":"http://google.com","shortUrl":"http://b1t.co/54"});

因此,当该get作为src加载到js中时,它将自动运行whateverJavascriptName,您应该将其实现为回调函数:

function minifyResultsCallBack(data)
{
    document.getElementById("results").innerHTML = JSON.stringify(data);
}

要实际执行JSONP调用,可以通过几种方式(包括使用jQuery)执行,但这里有一个纯JS示例:

function minify(urlToMinify)
{
   url = escape(urlToMinify);
   var s = document.createElement('script');
   s.id = 'dynScript';
   s.type='text/javascript';
   s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
   document.getElementsByTagName('head')[0].appendChild(s);
}

一个循序渐进的示例和一个要练习的jsonp web服务可以在以下位置获得: