【问题标题】:AngularJS, ngResource - Unexpected token ErrorAngularJS,ngResource - 意外的令牌错误
【发布时间】:2014-08-05 22:49:20
【问题描述】:

编辑:

我得到了错误但没有解决方案。似乎“isEditable”、“isOnline”和“isRecycled”不是作为布尔值而是作为字符串发送的。因此我的验证没有通过,错误响应不是有效的 JSON。

但为什么 .save() 调用将布尔值作为字符串发送?


原帖

谁能告诉我为什么下面的函数会抛出

SyntaxError: Unexpected token '

在 Object.parse(本机)

在 fromJson (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js:1072:14)

由于我的 postData 记录正确,我认为我的资源保存有错误。在服务器端,我有一个使用 Symfony2 组件制作的简单的自制 php 框架,资源的 $save 调用在我的数据库中添加了一个新行并将该行作为 JSON 对象返回。

        $scope.createStructure = function($event, createdStructure){
        $event.preventDefault();
        if(createdStructure.copy != null){
            copyId = createdStructure.copy.id;
        } else {
            copyId = 0;
        }
        postData = {
            'title': createdStructure.title,
            'id': copyId,
            'isEditable': false,
            'isOnline': false,
            'isRecycled': false
        }
        console.log(postData);
        Structure.save({}, postData, function(response){
            console.log(response);
            console.log(newStructure);
        });
    }

【问题讨论】:

  • createdStructure.title 中是否有偶然的单引号?您能否提供console.log(postData); 行之外的示例?尝试在 anugular.js 的第 1072 行添加断点并检查传递给 fromJson 的内容。
  • Object {title: "dgfgdfg", id: 0, isEditable: false, isOnline: false, isRecycled: false}

标签: javascript angularjs symfony ngresource


【解决方案1】:

PHP 无法判断传入的数据类型。POST 数据被视为字符串。检查此previous answer。我相信它涵盖了您遇到的问题。

PHP 也有FILTER_VALIDATE_BOOLEAN,我链接的答案中也有提到。我想它会对你有所帮助。

例如:

$isEditable= filter_var ($_POST['isEditable'], FILTER_VALIDATE_BOOLEAN);

这应该使 $isEditable 成为布尔值。

【讨论】:

  • 谢谢伙计,这真的帮助解决了我的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 2011-12-20
  • 2015-11-19
  • 2018-08-27
相关资源
最近更新 更多