JSONP跨域

1 概述

定义

json存在的意义:

不同类型的语言,都能识别json

JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题。由于同源策略,一般来说位于 server1.example.com 的网页无法与不是 server1.example.com的服务器沟通,而 HTML

image-20240731100716457

  • 跨域:浏览器A服务器B获取的静态资源,包括Html、Css、Js,然后在Js中通过Ajax访问C服务器的静态资源或请求。即:浏览器A从B服务器拿的资源,资源中想访问服务器C的资源。
  • 同源策略:同一个请求协议(如:Http或Https)、同一个Ip、同一个端口,3个全部相同,即为同源。

2 demo

后端

<?php
    $arr=["name"=>"woniu","age"=>20];
    //把数组转成json字符串,
    $json = json_encode($arr);
    //输出
    echo $json;
?>

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1.min.js"></script>
</head>
<body>
    <h1>前端</h1>
    <script>
        $.getJSON("后端的地址",function(data){
            alert(JSON.stringify(data));
        })
    </script>
</body>
</html>

用户访问

192.168.190.134/woniu/demo31.html

查看控制台:

image-20240731102921872

解决方案

  • JSONP
  • CORS

3 JSONP

image-20240731105929545

image-20240731112347075

后端

<?php
    $arr=["name"=>"woniu","age"=>20];
    //把数组转成json字符串,
    $json = json_encode($arr);
	$callback = $_GET["callback"]; // 函数对象, 字符串

    //输出
    ///echo $json;
	echo "$callback('$json')";
?>

前端

# 方法一:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.7.1.min.js"></script>
</head>
<body>
    <h1>前端</h1>
    <script>
        // function xxx(data){
        //     // 后端返回的data json
        //     console.log("999");
        // }
    </script>
    <script>
        $.getJSON("http://192.168.190.133/wh069/demo31.php?callback=?",function(data){
            alert(JSON.stringify(data));
            // alert(JSON.parse(data));  // 反序列化 
            // json:序列化和反序列化
        })
    </script>
</body>
</html>

# 方法二:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.7.1.min.js"></script>
</head>
<body>
    <h1>前端</h1>
    <script>
        function xxx(data){
            // 后端返回的data json
            alert(JSON.stringify(data));
        }
    </script>
    <script src="http://192.168.190.133/wh069/demo31.php?callback=xxx">
    </script>
</body>
</html>

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值