SONP 是什么

JSONP 是什么

说实话,我学了这么久,其实也没有好好了解这个东西,当然平常自己在前端方面也涉猎较浅。

1) jsonp 是什么

JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的 跨域 数据访问的问题。

跨域? 由于同源策略的原因,也就是说你请求资源时,浏览器对于不是你当前域名或者端口号都相同的地址给与禁止访问,不允许你获取资源

同源策略:

  • examle.com:8080 与 examle.com:9090 不同源
  • examle.com:8080 与 examle.com:9090 不同源
  • a.examle.com 与 examle.com 不同源

2) 如何解决同源策略带来的问题

浏览器中对<script>、<img>、<iframe> 是给予支持的,所以我们可以采用类似引用数据的方式来获取资源

处理流程:

  • 远程服务器取得js前端处理数据的函数名
  • 将相关需要返回的数据保存
  • 将数据串进行拼接,以函数的方式返回:showData(['a','b'])

3) 使用例子


    // JS
    &lt;button class="getRequest"&gt;发起跨域请求&lt;/button&gt;
    &lt;textarea name="" id="" cols="30" rows="10" disabled&gt;&lt;/textarea&gt;

    &lt;script&gt;
        function showdata(result) {
            console.log(result);
        }
        $('.getRequest').on('click', function(){
        //1) // $('head').append("&lt;script src='http://localhost/jsonp/service.php?jsonp=showdata'&gt;&lt;/script&gt;");
        
        //2)
            $.ajax({
                url : 'http://localhost/jsonp/service.php',
                type: 'GET',
                dataType: 'jsonp',
                jsonp: 'jsonp', // 自定义,保证后端能通过这个key值获取函数名
                jsonpCallback: "showdata",//自定义的jsonp回调函数名称
                success: function (json) {
                    alert('success');
                },
                error: function () {
                    alert('fail');
                }
            })
        })
    &lt;/script&gt;


    --------------------


    header('Content-type: application/json');
    //获取回调函数名
    $jsonp = htmlspecialchars($_REQUEST ['jsonp']);
    //json数据
    $json_data = '["customername1","customername2"]';
    //输出jsonp格式的数据
    echo $jsonp . "(" . $json_data . ")";  // 格式进行拼接,得到showdata(["customername1","customername2"]);


    --------------


由此可见,其实就是远程服务器代前端处理了相关函数,通过返回一个带参数的函数表达式,来进行执行相关逻辑代码。 有效避免了直接向远程服务器请求数据

原文地址:https://segmentfault.com/a/1190000016707550

原文地址:https://www.cnblogs.com/lalalagq/p/9906615.html