首页 > AngularJS 用 $http.jsonp 方法跨域请求数据错误的问题

AngularJS 用 $http.jsonp 方法跨域请求数据错误的问题

以前知道AngularJS是个什么东西,今天刚开始动手尝试,遇到了这个问题。

代码如下:

$http.jsonp("https://request.address.json?callback=JSON_CALLBACK")
    .success(
        function(data, status, header, config){
            $scope.list = data;
            alert(data);
        }
    )
    .error(
        function(data){
            alert("error");
        }
    );

访问后通过浏览器的开发者工具能看到返回的状态码是200,并且能看到返回的json字符串,但是执行后总是error方法被调用,找了很久也找不到解决办法,有么有高手能解答一下。


楼主解决了吗? 我也遇到跟你一样的问题, 浏览器上能正常走到success,手机上调试总是进入error, data=undefined status:404


客户端方面,官方文档说的很清楚的“Relative or absolute URL specifying the destination of the request. The name of the callback should be the string JSON_CALLBACK.”服务端的话,get到的callback参数就是angular在客户端计算过的angular.callbacks._0之类的(在发送之前angular会根据客户端的请求次数做计算,更新callback字段值),服务端接收到callback字段后,以字符串'angular.callbacks._0({json数据})'返回就可以了,比如:

<?php
$callback = $_GET['callback'];
$response = array('code'=>200, 'data'=>'success');

$json = json_encode($response);
echo "$callback($json)";

参数为callback=JSON_CALLBACK,angular会自动为你替换你的JSON_CALLBACK并分配callbackName。
你能请求到数据,但无法走进sccess里面,是因为没有触发angular为你设置的callback。我觉得这个略坑,没有jQuery设计的贴近用户


贴出返回的json看看


jsonp(url,[config])只能处理JSONP格式的结果(JSON != JSONP),如果你返回的数据是JSON格式,jsonp()是无法解析的,会报错。


后端接口需要对 jsonp 的请求做特殊的处理,请求带了 callback 的参数:

返回应该是一段 JavaScript 代码:

angular.callbacks._0({
    "longitude": 120.1614,
    "latitude": 30.2936,
    "asn": "AS4837",
    "offset": "8",
    "ip": "60.12.58.161",
    "area_code": "0",
    "continent_code": "AS",
    "dma_code": "0",
    "city": "Hangzhou",
    "timezone": "Asia\/Shanghai",
    "region": "Zhejiang",
    "country_code": "CN",
    "isp": "CNCGROUP China169 Backbone",
    "country": "China",
    "country_code3": "CHN",
    "region_code": "02"
});

这个和 JSONP 可以跨域的特新相关,JSONP 是使用 script tag 作为请求的载体的;而 Ajax 是通过 XHR 对象。


楼主解决了吗? 我也遇到跟你一样的问题。
控制台显示:JSON_CALLBACK is not defined

$http.jsonp('http://m-static.igrow.cn/01tpl/json/data.json?callback=JSON_CALLBACK');
//加上这个就能调到数据、但是感觉很奇怪。
window.JSON_CALLBACK = function(data) {

console.log(data);

};

假如我需要在返回error的时候执行其他事情又该怎么做?


返回内容改成:

JSON_CALLBACK({
    "longitude": 120.1614,
    "latitude": 30.2936,
    "asn": "AS4837",
    "offset": "8",
    "ip": "60.12.58.161",
    "area_code": "0",
    "continent_code": "AS",
    "dma_code": "0",
    "city": "Hangzhou",
    "timezone": "Asia\/Shanghai",
    "region": "Zhejiang",
    "country_code": "CN",
    "isp": "CNCGROUP China169 Backbone",
    "country": "China",
    "country_code3": "CHN",
    "region_code": "02"
})

试试?

【热门文章】
【热门文章】