【问题标题】:AngularJS Uncaught SyntaxError: Unexpected token :AngularJS Uncaught SyntaxError: Unexpected token :
【发布时间】:2016-01-31 18:49:10
【问题描述】:

好的,我尝试了几次,但没有任何效果

检查了以下答案

  1. questions/26262235/jsonp-returning-uncaught-syntaxerror-unexpected-token-angularjs-routingnu

  2. questions/16344933/angularjs-jsonp-not-working/16352746#16352746

  3. questions/19269153/jsonp-request-in-angularjs-doesnt-work-like-in-jquery

  4. questions/19669044/angularjs-getting-syntax-error-in-returned-json-from-http-jsonp

他们都没有解决我的问题。

我想使用 Giant Bombs API:http://www.giantbomb.com/api/

是的,我看了论坛帖子,没有任何效果。

$http({
        method: 'JSONP',
        url: 'http://www.giantbomb.com/api/game/3030-4725/',
        params: {
            api_key: $rootScope.api_key,
            format: 'jsonp',
            callback: 'JSON_CALLBACK'
        }
    }).then(function (data) {
        $scope.data = data;
        console.log($scope.data)
    });

错误

Uncaught SyntaxError: Unexpected token :

有人可以给我一个提示吗?

因为它真的很令人沮丧,我什至用 JSON_CALLBACK() 包装数据,结果相同

【问题讨论】:

  • 能否在出错的地方添加完整的代码,可以从控制台获取提示
  • 我想您检查了代码本身是否没有 SyntaxError。因此,“意外冒号”将出现在响应中。 Jsonp是封装在函数调用中的javascript对象。请提供响应代码。

标签: javascript angularjs request jsonp


【解决方案1】:

这样做的原因是,angular需要服务返回jsonp,但它没有

您的代码执行此请求:

http://www.giantbomb.com/api/game/3030-4725/?json_callback=angular.callbacks._0&format=jsonp

在网络控制台中你可以看到响应:

{"error":"'jsonp' format requires a 'json_callback' arguement","limit":0,"offset":0,"number_of_page_results":0,"number_of_total_results":0,"status_code":103,"results":[]}

所以回调的参数应该命名为:json_callback,而不仅仅是回调。

$http({
        method: 'JSONP',
        url: 'http://www.giantbomb.com/api/game/3030-4725/',
        params: {
            format: 'jsonp',
            json_callback: 'JSON_CALLBACK'
        }
    })

之后,我可以看到有关 api 密钥的响应错误 - 这在您的实例中可能没问题。所以我想你会得到正确的 JSONP

http://www.giantbomb.com/api/game/3030-4725/?json_callback=angular.callbacks._0&format=jsonp

{"error":"Invalid API Key","limit":0,"offset":0,"number_of_page_results":0,"number_of_total_results":0,"status_code":100,"results":[]}

另一个问题是你的函数 then 并没有直接获取数据,而是响应,即携带数据的对象,所以:

.then(function (response) {
        $scope.data = response.data;
        console.log(response.data)
    });

最后一个建议,不要在控制器中使用$scope,而是使用“controller as”语法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-17
    • 2019-02-10
    • 2014-07-08
    • 2011-03-09
    • 2014-01-06
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多