fromJson()中的AngularJS意外标记

时间:2013-09-08 00:02:39

标签: javascript json angularjs angularjs-service

以下代码行:

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) 

所以,我在779行的angular.js处放了一个断点。那里的代码是:

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

传递到json的{​​{1}}的值是“mnp801fap6kor50trgv4cgk7m2”。

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

请帮忙。我几个小时就撞到了这个头。

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

提前致谢!!!

2 个答案:

答案 0 :(得分:23)

$cookieStore似乎不是为了读取$cookieStore未创建的Cookie。来自评论:

* @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);
}

答案 1 :(得分:0)

Or you can simply wrap the $cookieStorage in a function and return a value or an empty string.

var sid = getPHPSESSID();

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

In that case you'll use the angular service with it's pros and if you don't put the key-value pair in cookies, you'll get the empty string in result