当前位置:Gxlcms > PHP教程 > javascript-js跨域请求

javascript-js跨域请求

时间:2021-07-01 10:21:17 帮助过:16人阅读

$.ajax({
        url : "http://apis.baidu.com/apistore/iplookupservice/iplookup?ip="+window.location.href,

        beforeSend: function(request) {
                        request.setRequestHeader("apikey", "1f5cb934618472891347834b2bf64c8d");
                    },
        type:"GET",
        dataType : "jsonp",
        success : function(data){
            console.log(data);
        }
    });

js请求数据失败。

php成功,为什么?

$ch = curl_init();
        $url = 'http://apis.baidu.com/apistore/iplookupservice/iplookup?ip='.$_SERVER['REMOTE_ADDR'];
        $header = array(
            'apikey:1f5cb934618472891347834b2bf64c8d',
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch , CURLOPT_URL , $url);
        $res = curl_exec($ch);

        $info = json_decode($res);

回复内容:

$.ajax({
        url : "http://apis.baidu.com/apistore/iplookupservice/iplookup?ip="+window.location.href,

        beforeSend: function(request) {
                        request.setRequestHeader("apikey", "1f5cb934618472891347834b2bf64c8d");
                    },
        type:"GET",
        dataType : "jsonp",
        success : function(data){
            console.log(data);
        }
    });

js请求数据失败。

php成功,为什么?

$ch = curl_init();
        $url = 'http://apis.baidu.com/apistore/iplookupservice/iplookup?ip='.$_SERVER['REMOTE_ADDR'];
        $header = array(
            'apikey:1f5cb934618472891347834b2bf64c8d',
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch , CURLOPT_URL , $url);
        $res = curl_exec($ch);

        $info = json_decode($res);

jQuery中type为jsonp的ajax是不允许自定义请求头的,虽然你在beforeSend里面加了自定义的头apikey,但是由于jsonp的实现是通过