【问题标题】:AngularJS unexpected token in fromJson()fromJson() 中的 AngularJS 意外标记
【发布时间】:2013-09-11 19:29:47
【问题描述】:

以下代码行:

var sid = $cookieStore.get('PHPSESSID');

正在抛出此错误:

SyntaxError: Unexpected token m
at Object.parse (native)
at Object.fromJson (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:779:14)
at Object.angular.module.factory.factory.get (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-cookies.js:149:34)
at Object.getAllImages (https://7-september.com/photoslide/js/services.js:29:36)
at new Management (https://7-september.com/photoslide/js/controllers.js:54:18)
at invoke (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2902:28)
at Object.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:2914:23)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:4805:24)
at update (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:14198:26)
at Object.$get.Scope.$broadcast (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js:8307:28) 

所以,我在 angular.js 的第 779 行设置了一个断点。代码如下:

777    function fromJson(json) {
778        return isString(json)
779            ? JSON.parse(json)
780            : json;
781    }

传递给JSON.parse()json 的值为“mnp801fap6kor50trgv4cgk7m2”。

我还注意到,传递给该方法的其他内容通常有两个引号,例如 ""userName""。

请帮忙。我为此苦苦思索了几个小时。

或者,如果有人知道使用 Angular 从 cookie 中获取 php 会话 id 的更好方法,那也很棒。 (是的,我可以使用 jQuery 或裸机 JS 来实现,但我更愿意继续使用 Angular)。

提前致谢!!!

【问题讨论】:

    标签: javascript json angularjs angularjs-service


    【解决方案1】:

    $cookieStore 似乎并不是要读取不是由$cookieStore 创建的 cookie。来自 cmets:

    * @description
    * Provides a key-value (string-object) storage, that is backed by session cookies.
    * Objects put or retrieved from this storage are automatically serialized or
    * deserialized by angular's toJson/fromJson.
    

    automatically serialized or deserialized 是重要部分。我能够在这里重现您的问题:http://jsfiddle.net/xtmrC/

    您可能想改用$cookies,如下所示:http://jsfiddle.net/MXTY4/9/

    angular.module('myApp', ['ngCookies']);
    function CookieCtrl($scope, $cookies) {
        console.log('haha', $cookies.PHPSESSID);
    }
    

    【讨论】:

    • 谢谢。实际上,我在发布它几分钟后就找到了答案,但由于我的代表不够高,八小时内无法发布答案。但感谢您的回复。你是对的。似乎在向 $cookieStore 添加一些东西的过程中,它还在值周围添加了一组额外的“”。所以,是的,你只能从你自己放置的 $cookieStore 中获取东西。并且使用 $cookies.PHPSESSID 效果很好。
    • 另外,我会赞成你的回答,但我不能因为我的代表不够高。
    • 我赞成你的问题..也许现在你可以?欢迎使用 StackOverflow!
    • @NishchitDhanani 已修复
    【解决方案2】:

    或者您可以简单地将 $cookieStorage 包装在一个函数中并返回一个值或一个空字符串。

    var sid = getPHPSESSID();
    
    function getPHPSESSID() {
       return $cookieStore.get('PHPSESSID') || '';
    }
    

    在这种情况下,您将使用角度服务及其优点,如果您不将键值对放入 cookie,您将在结果中获得空字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多