【问题标题】:Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse未捕获的 SyntaxError:JSON.parse 处的 JSON 输入意外结束
【发布时间】:2019-07-10 02:08:55
【问题描述】:

我正在尝试将数据从 JSON 加载到我的网站。一切正常运行了一段时间,但今晚我突然开始收到以下错误。 (到目前为止它在本地主机上工作)

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at FileReader.<anonymous>

调用 JSON 的 Javascript 如下:

function readJSON(path) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', path, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) { 
        if (this.status == 200) {
            var file = new File([this.response], 'temp');
            var fileReader = new FileReader();
            fileReader.addEventListener('load', function(){
                // do stuff with fileReader.result
                var volant = JSON.parse(fileReader.result);
                // console.log(volant);   
            });
            fileReader.readAsText(file);
        } 
    }
    xhr.send();
}

readJSON('https://volant.inexsda.cz/v1/workcamps.json');

我需要从 JSON 中读取数据,但现在我不能了。有人可以帮忙吗?

编辑:在 Safari 上一切正常。该问题出现在 Chrome 中。

【问题讨论】:

  • 您是否已经检查过您从 HttpRequest 收到的内容?请添加console.log(fileReader.result)。发布该结果并自行检查其正确性。
  • 您确定响应类型是“blob”吗? Blob 是一个包含二进制数据的对象。 developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
  • console.log(fileReader.result) 为空
  • 不确定“blob”。整个“有趣”的问题是代码在几个小时前就可以工作,而我没有对其进行任何更改。此外,它适用于 Safari 和 Firefox。只有 Chrome 这样做:(
  • console.log(fileReader.result) 在 Safari 中显示 JSON 文件的内容(在 Chrome 中为空)

标签: javascript json cross-origin-read-blocking


【解决方案1】:

正如@abestrad 指出的那样,xhr.responseType = 'blob'; 是一个可能的问题,应该是json,如here 所述。

更新: 尝试以下方法,这在同一域的 chrome 中对我有用:

function readJSON(path) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', path, true);
    xhr.responseType = 'json';
    xhr.onreadystatechange  = function(e) { 
        if (xhr.readyState == 4) {
            if (this.status == 200) {
                console.log(this.response);
            } 
        }
    }
    xhr.send();
}

readJSON('https://volant.inexsda.cz/v1/workcamps.json');

【讨论】:

  • 好的。我改变了它,但现在 fileReader.result 为空
  • @JakubŠnorbert,当您发出请求时,网络选项卡会显示什么?响应的标头中可能有一些内容可以提供更多信息。
  • 请求 URL:volant.inexsda.cz/v1/workcamps.json?page=1 请求方法:GET 状态码:200 OK 远程地址:83.167.225.248:443 推荐人策略:no-referrer-when-downgrade Access-Control-Allow-Headers:授权,x-goog-authuser Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE Access-Control-Allow-Origin: * Allow: POST, GET, OPTIONS, PUT, DELETE 显示临时标题来源:@ 987654323@Referer:localhost:8888/aktivity/workcampy/kratkodobe-workcampypage:1
  • 你不是在进行跨域调用吧?
  • 在本地主机上运行,​​跨域调用除外
猜你喜欢
  • 2018-12-09
  • 2021-06-08
  • 1970-01-01
  • 2020-10-05
  • 2022-01-22
  • 2020-03-09
  • 2021-02-27
  • 2020-02-06
  • 2017-01-05
相关资源
最近更新 更多