programing

"Uncatched SyntaxError"의 원인:$.parseJSON() 및 JSON.parse()가 포함된 예기치 않은 토큰 o"

luckcodes 2023. 2. 11. 23:49

"Uncatched SyntaxError"의 원인:$.parseJSON() 및 JSON.parse()가 포함된 예기치 않은 토큰 o"

SO와 구글을 다 찾아봤지만 그게 도움이 되었고 어떻게 계속해야 할지 모르겠어요.php 페이지에서 반환하는 어레이가 있습니다.echo json_encode()다음과 같이 표시됩니다.

[" "," "," "," "," ",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]

근데 자꾸...Unexpected token o at Object.parse (native)JSON.parse()를 사용하려고 하면Unexpected token o at Function.parse (native)JQuery를 사용할 때 사용합니다.

그냥 붙이면$scope페이지를 사용하여 출력할 수 있는데, 제가 무엇을 잘못하고 있으며 어떻게 수정해야 합니까?

이것은 내 컨트롤러입니다.

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;
    //
}

서비스 방법은 다음과 같습니다.

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입니다.

<?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); ?>

시도해 본 것

반품할 경우typeof오브젝트를 취득했기 때문에, 그 후 시도했습니다.var monthDays = Array.prototype.slice.call(response)그리고.var monthDays = $.map(response, function (value, key) { return value; });여기 몇 가지 답변에서 제시된 바와 같이, 나는 또한 시도했다.JSON.stringify()하지만 난 그저{}결과적으로

나는 이것에 대해 정말 좌절했다. 나를 올바른 방향으로 인도해 줄 누군가가 정말로 필요하다.

갱신하다

이것은, 사용의 문제가 될 가능성이 있다고 생각합니다.$q.defer()get Month 메서드를 다음과 같이 업데이트했습니다.

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;
}   

이제 알겠다1위해서console.log("data " + data[0]);예상대로지만 나는 이해한다console.log(month);나는 이해한다[object Object]위해서console.log(month.promise)나는 이해한다[object Object]및 을 위해console.log(month.promise[0]);나는 이해한다undefined

response는 이미 해석되었으므로 다시 해석할 필요가 없습니다.

다시 해석하면 먼저 toString-cast가 실행되므로 해석합니다.

"[object Object]"

이 때문에unexpected token o.

$http 모듈의 Transforming Requests and Response 장을 참조하십시오.

JSON 응답이 검출되었을 경우는, JSON 파서를 사용해 역직렬화합니다.

이미 JSON 오브젝트로 해석되어 있기 때문에 다시 해석하면 그 에러가 발생합니다.

간단한 테스트는 다음과 같습니다.

response = '{"a": "a","b": "b"}';
var obj = $.parseJSON(response);
console.log(obj); //Object {a: "a", b: "b"} 
$.parseJSON(obj)  //Uncaught SyntaxError: Unexpected token o 

이 문제는 @CuongLe를 사용하여 해결되었습니다.

 response = memberFactory.getMonth("2013-08-01 06:30:00");
 var monthDays = $.parseJSON(response);

포함:

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

헤더가 송신되는 경우:

Content-Type: text/json

그리고나서parseJSON()를 호출할 필요가 없습니다.예를 들어 다음과 같습니다.

PHP에서는 헤더를 다음과 같이 설정합니다.

<?php
header("Content-Type: text/json");
echo json_encode(array("someKey" => "someValue"));

Javascript에서 성공 함수는 다음과 같습니다.

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

언급URL : https://stackoverflow.com/questions/18130081/what-is-causing-uncaught-syntaxerror-unexpected-token-o-with-parsejson-an