在PHP中将数组传递到AJAX请求时,如果JSON中出现意外的标记"C",这通常是由于编码问题或者数据序列化不正确导致的。以下是一些可能的原因和解决方法:
假设你有一个PHP脚本data.php
,它返回一个JSON格式的数组:
<?php
header('Content-Type: application/json; charset=utf-8');
$yourArray = ['item1', 'item2', chr(0).'item3']; // 假设这里有一个包含控制字符的元素
function cleanForJson($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
$data[$key] = cleanForJson($value);
}
} else if (is_string($data)) {
$data = preg_replace('/[\x00-\x1F\x7F]/', '', $data); // 移除控制字符
}
return $data;
}
$cleanArray = cleanForJson($yourArray);
echo json_encode($cleanArray);
?>
在AJAX请求中,你可以这样处理返回的数据:
$.ajax({
url: 'data.php',
method: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
通过上述方法,你应该能够解决PHP数组传递到AJAX时JSON中出现意外标记"C"的问题。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云