php函数file_get_contents应对百度天气接口CORB跨域解决方案

在调用百度天气接口时,出现如下CORB跨域错误提示

jquery.js:4 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://api.map.baidu.com/weather/v1/?district_id=330200&data_type=all&ak=F552bedbee2ec8fa6bae&callback=jQuery21401369341023950672_1587783673994&_=1587783673995 with MIME type application/javascript. See https://www.chromestatus.com/feature/5629709824032768 for more details.

历经jquery中ajax处理跨域中的处理方式$getJSON、jsonp都不得其法,后端又不变设置NGIX代理或设置header,思路如下:
所谓同源,简单的理解就是域名和访问协议必须完全相同,而调用第三方API,是客观上解决不了的。但是在自己的服务器上却是可以随时解决同源的问题?

基于此思路,豁然开朗:
一、新建weather.php文件,通过file_get_contents获取JSON字符串,并在文件中打印出来

header("Content-type:text/html;charset=utf-8");
//01.获取JSON数据;
$url  = "http://api.map.baidu.com/weather/v1/?district_id=330200&data_type=all&ak=F552bedbee2ec8fa6bae7b7";
$cont = file_get_contents($url);
echo $cont;

二、新建index.html,通过ajax获取weather.php:

    $(function () {
        var url = "weather.php";

        $.get(url, function (data) {
            var json = jQuery.parseJSON(data);
            console.log(typeof(json));
            console.log(json.result.location.city);
        })


    })

Done!

猜你喜欢

转载自blog.csdn.net/weixin_41290949/article/details/105746384