WEB - JSONP

JSON with Padding参考

  1. https://zh.wikipedia.org/wiki/JSONP
  2. http://www.runoob.com/json/json-jsonp.html

使用步骤

  1. 在<script>中写一个回调函数。
  2. 在<script>中的src写API的地址(参数中写jsonp=回调函数名字),即是用GET向服务器的API发出request。(因为<script>不受同源政策限制,可以向服务器获取数据)
  3. 服务器返回的response是callBackFunction(json_data);(因为先前客户端写了同名的回调函数,所以response返回后在客户端触发这个函数)。
  4. Padding的意思就是客户端触发callBackFuntion(json_data),从参数中获取JSON数据,填充到客户端所需求的标签的值;(如果返回的直接是JSON,Browser无法解释处理,无法触发);

另外,服务器端拼接callBackfuntion(xxx),xxx可以不是JSON_data,不过一般是JSON_data;

Talk is cheap, Show me the freaking code

  1. 客户端

    
    <script type="text/javascript">
        // 写回调函数,GET请求返回时触发,处理参数中的response(因为服务器端是把回调函数callBackFunction()和JSON_data拼接在一起,使JSON_data变成了callBackFunction的参数response)
        function parseQuote(response) {
            document.getElementById("quote").innerHTML = response.quoteText;
            document.getElementById("author").innerHTML = response.quoteAuthor;
        }
    </script>
    
    <script type="text/javascript"
            src="http://api.forismatic.com/api/1.0/?method=getQuote&amp;format=jsonp&amp;lang=en&amp;jsonp=parseQuote"
            async></script>
  2. 服务端(只是模拟,本质是返回一段字符串,这段字符串是客户端可以触发、解析的JavaScript代码

    <?php
    header('Content-type: application/json');
    //获取回调函数名
    $jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
    //json数据
    $json_data = '["customername1","customername2"]';
    //输出jsonp格式的数据
    echo $jsoncallback . "(" . $json_data . ")";
    ?>

另外

  1. JSONP是规避同源策略的一种方法
  2. Due to inherent insecurities, JSONP is being replaced by CORS

猜你喜欢

转载自www.cnblogs.com/allen2333/p/9185511.html