在我的控制器中,我使用ajax处理POST请求,并将来自GET请求的数据直接添加到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..
}
当我用ajax调用它时一切正常但是当我尝试直接运行handleResponseData()
时,我会对特殊字符进行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;
}
为什么json字符串在使用jquery $.post
获取时解析得很好,但是在手动嵌入到代码中时却没有解析?我该如何解决这个问题?
修改:
从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"}]}
答案 0 :(得分:1)
问题是由Line breaks
引起的。
正如jQuery.parseJSON()文档所述:&#34;控制字符&#34;例如,不允许使用制表符或换行符。
当使用$.post
进行呼叫时,新的线路字符转换为字符串"\r\n"
,这就是为什么这种情况有效。
添加这样的东西来删除新行最终解决了它。
function stripNewLines(&$mValue) {
if(is_string($mValue)) {
$mValue = trim(preg_replace('/\s+/', ' ', $mValue));
}
}
array_walk_recursive($aResponse, 'stripNewLines');
答案 1 :(得分:-1)
在PHP控制器中,在echo JSON响应之前键入以下行
header("Content-Type: application/json");
并且在jQuery Ajax调用中你需要提到数据类型为JSON
$.ajax({
...,
...,
dataType: 'JSON', // it is necessary to get JSON response
...
});