What is causing “Uncaught SyntaxError: Unexpected token o” with $.parseJSON() and JSON.parse()
我到处都是这样和谷歌,但也注意到这有帮助,我不确定如何继续。我有一个数组,我使用
1 | ["","","","","",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31] |
但是当我尝试使用json.parse()时,我总是得到
但是当我把它附在
这是我的控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function myController($scope, memberFactory) { response = memberFactory.getMonth("2013-08-01 06:30:00"); //$scope.response = response; var monthDays = $.parseJSON(response); var dates = []; for (var i = 0; i < monthDays.length; i++) { if (i % 7 == 0) dates.push([]); dates[dates.length - 1].push(monthDays[i]); } $scope.dates = dates; // } |
这是我的服务方式:
1 2 3 4 5 6 7 8 9 10 | obj.getMonth = function (date) { var month = $q.defer(); $http.get('getMonth.php?date=' + date) .success(function (data, status, headers, config) { month.resolve(data); }); return month.promise; } |
这是我的PHP:
1 2 | <?php $daysOfMonth=["","","","","",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]; echo json_encode($daysOfMonth); ?> |
我试过的东西
如果我退回
我真的很沮丧,真的需要有人指点我正确的方向。
更新我认为这可能是使用
1 2 3 4 5 6 7 8 9 10 11 12 | obj.getMonth = function (date) { var month = $q.defer(); $http.get('getMonth.php?date=' + date) .success(function (data, status, headers, config) { month.resolve(data); console.log("data" + data[0]); console.log("resolved" + month.promise[0]); }); return month.promise; } |
现在我按预期得到了
如果您再次分析它,它将首先执行ToString转换,因此您正在分析
1 | "[object Object]" |
这就解释了
请看一下转换$http模块请求和响应的章节。
If JSON response is detected, deserialize it using a JSON parser.
因为它已经被解析为JSON对象,如果您再次解析它,您将得到这个错误。
下面是一个简单的测试:
1 2 3 4 | response = '{"a":"a","b":"b"}'; var obj = $.parseJSON(response); console.log(obj); //Object {a:"a", b:"b"} $.parseJSON(obj) //Uncaught SyntaxError: Unexpected token o |
如果发送了标题:
1 | Content-Type: text/json |
那么不需要调用
在一个PHP中,我将像这样设置头部:
1 2 3 | <?php header("Content-Type: text/json"); echo json_encode(array("someKey" =>"someValue")); |
在javascript中,对于success函数,我有类似的功能:
1 2 3 4 5 | success: function(response) { // This will output"someValue" to the console. // Note the lack of the parseJSON() call. parseJSON() is called for us because the header was sent as text/json console.log(response.someKey); } |
这是在@cuongle的帮助下通过替换
1 2 | response = memberFactory.getMonth("2013-08-01 06:30:00"); var monthDays = $.parseJSON(response); |
用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | response = memberFactory.getMonth("2013-08-01 06:30:00"); response.then( function (monthDays) { console.log("monthDays :" + monthDays +" !!!"); var dates = []; for (var i = 0; i < monthDays.length; i++) { if (i % 7 == 0) dates.push([]); dates[dates.length - 1].push(monthDays[i]); } $scope.dates = dates; }); |