在我的控制器中,我用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
。
我的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)
剥离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"}]}
后
{"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()文档所述:不允许使用制表符或换行符等"控制字符"。
当用$.post
调用时,新行字符被转换为字符串"'r'n"
,这就是为什么这种情况有效的原因。
添加这样的东西来删除新行最终解决了这个问题
function stripNewLines(&$mValue) {
if(is_string($mValue)) {
$mValue = trim(preg_replace('/'s+/', ' ', $mValue));
}
}
array_walk_recursive($aResponse, 'stripNewLines');
在PHP控制器中,在echo JSON respose之前,键入以下行
header("Content-Type: application/json");
而且在jQueryAjax调用中,您需要提到数据类型为JSON
$.ajax({
...,
...,
dataType: 'JSON', // it is necessary to get JSON response
...
});