[英]Uncaught SyntaxError: Unexpected token - JSON character encoding
在我的控制器中,我使用ajax處理POST請求,並將GET請求中的數據直接添加到js代碼中
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..
}
當我用ajax調用它時,一切正常,但是當我嘗試直接運行handleResponseData()
,我得到了Uncaught SyntaxError: Unexpected token
特殊字符上的Uncaught SyntaxError: Unexpected token
。
我的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);
});
最后是我的轉換方法
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;
}
當使用jquery $.post
來獲取json字符串時,為什么解析得很好,但是當手動嵌入到代碼中時卻無法解析呢? 我該如何解決這個問題?
編輯 :從console.log(rawData)
精簡版本的rawData
得到
{"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"}]}
問題是由Line breaks
引起的。
如jQuery.parseJSON() docs所述:不允許使用“控制字符”,例如制表符或換行符。
當用$.post
調用時,新的行字符被轉換為字符串"\\r\\n"
,這就是這種情況起作用的原因。
添加這樣的東西以刪除新行最終解決了它。
function stripNewLines(&$mValue) {
if(is_string($mValue)) {
$mValue = trim(preg_replace('/\s+/', ' ', $mValue));
}
}
array_walk_recursive($aResponse, 'stripNewLines');
在您的PHP控制器中,在回顯JSON重新放置之前,輸入以下行
header("Content-Type: application/json");
並且在jQuery Ajax調用中,您需要將數據類型提到為JSON
$.ajax({
...,
...,
dataType: 'JSON', // it is necessary to get JSON response
...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.