我正在尝试使用 ajax 读取文件,但出现错误
语法错误:JSON.parse:JSON 数据第 1 行第 48 列的 JSON 数据后出现意外的非空白字符
因为经过检查,我总是以 ""
作为最后一条记录......?!
这是 test.txt
文件:
one
two
three
这是我的 ajax 调用:
$.ajax( {
url: 'control.php',
type: "post",
dataType: "json",
data: details,
success: function(data, textStatus) {
$("#whitelist").append(data[0])
},
complete: function(jqXHR, responseText) {
// alert('complete')
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error');
// var responseText = jQuery.parseJSON(jqXHR.responseText);
console.log(errorThrown);
}
});
这里是 control.php
,它读取文件并返回一个 json 编码的数组:
$path = "test.txt";
$file = fopen($path, 'r');
$data = fread($file, filesize($path));
fclose($file);
$lines = explode(PHP_EOL,$data);
error_log('Lines: ' . json_encode($lines, JSON_FORCE_OBJECT) . "err: " . json_last_error());
error_log('Lines: ' . serialize($lines));
echo json_encode($lines, JSON_FORCE_OBJECT);
这是error_log()
输出:
Lines: {"0":"one","1":"two","2":"three","3":""} json_last_error: 0
这是 Firebug 的输出:
{"0":"one","1":"two","2":"three","3":""}{"error":"Error","message":[]}
已经几个小时了!!这个 ""
到底是从哪里来的?另外,为什么 json_last_error() 根本没有帮助?为什么构建一个简单的 json 数组这么难?
我显然做了一些非常错误的事情。请带我走向光明,我已经筋疲力尽了。
最佳答案
由于您无论如何都要将文件的全部内容读入内存,因此有一种更简单的方法可以通过换行符/换行符将其分割并忽略空行
$data = file($path, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
echo json_encode($lines, JSON_FORCE_OBJECT);
关于PHP json_encode错误: Empty last record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33315324/