jsonp jquery 实现 跨域 服务端 php

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zyddj123/article/details/82704339

注: jsonp只支持get方式


html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
    <script src="./jquery-3.3.1.min.js"></script>
    <script>
        (function(){
            $.ajax({
                url: "http://192.168.1.111/jsonp.php",
                type: "get",
                dataType : "jsonp",
                data: "",
                success: function (data) {
                    console.log(data);
                },
                error: function () {
                    console.log("error");
                }
            });
        })();
    </script>
</body>
</html>

php

<?php 
$jsonp = $_GET['callback'];//get接收jsonp自动生成的函数名
$arr = array(
    'id' => 'asdf',
    'name' => 'eric'
);
echo $jsonp.'('. json_encode($arr). ')'; //jsonp函数名包裹json数据
?>

效果如下:

这里写图片描述



这里写图片描述



这里写图片描述

猜你喜欢

转载自blog.csdn.net/zyddj123/article/details/82704339