简体   繁体   中英

Uncaught SyntaxError: Unexpected token - JSON character encoding

In my controller I handle POST requests with ajax and adds data from GET requests directly to the js-code

mycontroller.php

$sServiceNumber = isset($_POST['ServiceNumber']) ? $_POST['ServiceNumber'] :  $_GET['ServiceNumber'];

//Here I do a db call for sServiceNumber and fetch some data as array $aAllrows

$aResponse['ServiceNumber'] = $sServiceNumber;
$aResponse['Data'] = $aAllrows;
$sJson = json_encode(self::convertToStrictUtf8($aResponse));

if (isset($_POST['ServiceNumber'])) {
    echo $sJson;
    exit;
} else {
    $sJs = '
    $(document).ready(function() {
        var sData = \'' . $sJson . '\';
        handleResponseData(sData);
    });';

    MyHtmlHead::addExtraJsCode($sJs);

    //continue with rendering html page here..
}

When I call this with ajax everything works fine but when I try to run handleResponseData() directly I get Uncaught SyntaxError: Unexpected token on special characters.

My JavaScript

function handleResponseData ( rawData ) {
    response = jQuery.parseJSON(rawData);  //<--this is where the error occurs (on GET requests)

    //Make use of response data
}

$("form[name='searchform']").submit(function( event ) {
    event.preventDefault(); 
    // Send post and fetch some data!
    $.post(baseUrl, { ServiceNumber: $("input[name='ServiceNumber']").val(), time: "2pm" }).done(handleResponseData);
});

Lastly here comes my conversion method

protected static function convertToStrictUtf8 ($p_aValues) {
    function detectEncoding(&$mValue) {
        if (!mb_detect_encoding($mValue, 'UTF-8', true)) {
            $mValue = utf8_encode($mValue);
        }
    }
    array_walk_recursive($p_aValues, 'detectEncoding');

    return $p_aValues;
}

How come the json string parses fine when fetched with jquery $.post but not when embedded into code manually? How do I solve this issue?

edit : Stripped down version of rawData from console.log(rawData)

GET

{"ServiceNumber":"485218-1138932068","Data":[{"RowId":"AEEA-IU3A61","ServiceRequestId":"AEEA-IU39LX","Name":"SV LIDEHÄLL)","FileSize":"8812","ServiceNumber":"485218-1138932068","Subject":"O(BERGMAN/LIDEHÄLL)
","Area":"svrT","Dir":"1702"}]} 

POST

{"ServiceNumber":"485218-1138932068","Data":[{"RowId":"AEEA-IU3A61","ServiceRequestId":"AEEA-IU39LX","Name":"SV LIDEH\u00c4LL)","FileSize":"8812","ServiceNumber":"485218-1138932068","Subject":"O(BERGMAN\/LIDEH\u00c4LL)\r\n","Area":"svrT","Dir":"1702"}]} 

The problem was caused by Line breaks .

As the jQuery.parseJSON() docs states: "control characters" such as a tab or newline is not allowed.

When calling with $.post the new line chars were converted to a string "\\r\\n" which is why that case was working.

Adding something like this to remove new lines finally solved it.

function stripNewLines(&$mValue) {
    if(is_string($mValue)) {
        $mValue = trim(preg_replace('/\s+/', ' ', $mValue));
    }
}
array_walk_recursive($aResponse, 'stripNewLines');

In your PHP controller, before echo JSON respose type the following line

header("Content-Type: application/json");

and also in jQuery Ajax call you need to mention data type as JSON

$.ajax({
 ...,
 ...,
 dataType: 'JSON', // it is necessary to get JSON response 
 ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM