jsonp解决跨域问题

文章通过三个测试例子详细解释了如何利用JSONP来解决浏览器的同源策略限制,实现跨域数据交互。从手动创建script标签到使用jQuery的AJAX方法,展示了JSONP的工作原理。同时,提到了更简单的解决方案,即在PHP服务器端设置响应头`Access-Control-Allow-Origin:*`来允许跨域请求。
摘要由CSDN通过智能技术生成

jsonp解决跨域问题

测试1:

a.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        var localHandler = function (data) {
            alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result);
        };
    </script>
    <script type="text/javascript" src="http://localhost/across_test/remote.js"></script>
</head>
<body>

</body>
</html>
remote.js
localHandler({"result": "this is the remote.js content!!!"});

浏览器访问, 响应结果如下:

在这里插入图片描述

测试2:

a.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        // 得到航班信息查询结果后的回调函数
        var flightHandler = function (data) {
            alert('你查询的航班结果是:票价 ' + data.price + ' 元,' + '余票 ' + data.tickets + ' 张。');
        };
        // 提供jsonp服务的url地址(不管是什么类型的地址,最终生成的返回值都是一段javascript代码)
        var url = "http://localhost/across_test/remote.js";
        // 创建script标签,设置其属性
        var script = document.createElement('script');
        script.setAttribute('src', url);
        // 把script标签加入head,此时调用开始
        document.getElementsByTagName('head')[0].appendChild(script);
    </script>
</head>
<body>

</body>
</html>
remote.js
flightHandler({
    "code": "CA1998",
    "price": 1780,
    "tickets": 5
});

访问效果:

在这里插入图片描述

测试3:

a.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <script type="text/javascript" src="http://localhost/across_test/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "get",
                async: false,
                url: "http://localhost/across_test/logic.php?code=CA1998",
                dataType: "jsonp",
                jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
                jsonpCallback: "flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
                success: function (json) {
                    console.log(json)
                    alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');
                },
                error: function () {
                    alert('fail');
                }
            });
        });
    </script>
</head>
<body>
</body>
</html>
logic.php
<?php
    
$json = json_encode([
    "code" => "CA1998",
    "price" => 1780,
    "tickets" => 5
]);
$callback = $_GET['callback'];
echo $callback . "($json)";

访问效果:

在这里插入图片描述


更简单的方式解决跨域请求
在PHP响应数据时, 添加一个响应头即可

a.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <script type="text/javascript" src="http://localhost/across_test/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "get",
                url: "http://localhost/across_test/logic.php?code=CA1998",
                success: function (json) {
                    console.log(json)
                },
                error: function () {
                    alert('fail');
                }
            });
        });
    </script>
</head>
<body>
</body>
</html>
logic.php

<?php

header('Access-Control-Allow-Origin: *');
$json = json_encode([
    "code" => "CA1998",
    "price" => 1780,
    "tickets" => 5
]);

echo $json;

效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值