【问题标题】:Uncaught SyntaxError: Unexpected token : in AngularJSUncaught SyntaxError: Unexpected token : in AngularJS
【发布时间】:2017-03-28 20:28:11
【问题描述】:

我已经为此工作了几个小时,但似乎无处可去。我希望这是发布此内容的正确位置。我是 StackOverflow 的新手,所以如果这不正确,请引导我到正确的地方。

我有以下 html 文件:

<!DOCTYPE HTML>
<html ng-app="DishClips">
 <head>
    <script type="text/javascript" src="http://code.angularjs.org/angular-1.0.0.0rc4.min.js"></script>
    <script type="text/javascript" src="http://code.angularjs.org/angular-resource-1.0.0.0rc4.min.js"></script>
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css">
    <script type="text/javascript" src="./dishclips.js"></script>
 </head>

 <body>
 <div ng-controller="DishClipsCtrl">
    <table class="table table-striped">
        <tr ng-repeat="restaurant in dishclipsResult.results"></tr>
            <td>{{restaurant.name}}</td>
    </table>
 </div>
 </body>
</html>

以及我的 discclips.js 中的以下内容:

angular.module('DishClips', ['ngResource']);

function DishClipsCtrl($scope, $resource) {
    $scope.dishclips = $resource('http://apiv2.dishclips.com/dishclips/api/:action',
    {action:'searchRestaurants',address:'irvine',callback:'JSON_CALLBACK' },
    {get:{method:'JSONP'}});

    $scope.dishclipsResult = $scope.dishclips.get(); 
}

当我运行这个(在 chrome 中)时,我得到:

Uncaught SyntaxError: Unexpected token :

json 返回看起来很棒,所以我不明白为什么这是一个问题。

谢谢

【问题讨论】:

  • 使用 Angular 的开发版本而不是缩小版本,然后告诉您的浏览器在异常之前中断。堆栈跟踪可能包含有用的信息。
  • 你解决了吗?

标签: angularjs


【解决方案1】:

因为您使用的 API 返回 JSON 而不是 JSONPJSONP 的有效载荷应该用类似 functionCall({"Name": "Foo", "Id": 1234, "Rank": 7}); 的函数包装

【讨论】:

  • 刚刚输入了这个确切的答案,但你打败了我。
  • 我不确定这到底是什么意思?我需要将代码的哪一部分包装在 fanctionCall 中?
  • @sza 你能帮我弄清楚这个函数需要去哪里吗?我不确定我是否理解有关如何解决此问题的提示。谢谢
  • @ksimons 你能帮忙吗?谢谢
  • 服务器端 API 需要将 JSON 结果包装在一个函数调用中,这就是 JSONP 的工作原理。由于我猜您无法控制此 API,因此您最好的选择是在服务器上创建一个 API 来为您的 Web 内容提供服务。该 API 应该只是将请求转发到其他 API。这将规避同源问题。
【解决方案2】:

您必须在 JSONP 请求中再定义一个默认参数。

get:{method:'JSONP', params : {callback : 'JSON_CALLBACK'}}

【讨论】:

    【解决方案3】:

    如果不小心将模板页面(而不是指令 .js 文件的顶部)加载为脚本,也会出现此错误。

    <script src="/js/Directives/Templates/myTemplate.html"></script>
    

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 2018-01-07
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      相关资源
      最近更新 更多