【问题标题】:Getting "not well-formed" in FF error when reading JSON from a local file从本地文件读取 JSON 时在 FF 错误中出现“格式不正确”
【发布时间】:2016-05-24 04:46:23
【问题描述】:

我正在我的计算机上处​​理一个项目,当我尝试从我计算机上的文件中读取 json 对象时遇到“格式不正确”的错误。

它发生在 Firefox 上。在 Chrome 中,我收到“XMLHttpRequest 无法加载文件...”。

我尝试将 Mime-type 更改为 application/json 但没有成功。

你能帮忙吗?


我的代码:

$.ajax({
    url: 'json/local_json_file.json',
    dataType: 'json',  //or application/json
    type: 'get',
    cache:'false',
    success: function(data) {
        $(data).each(function(index,value) {
            //some code
        });
    }
});

【问题讨论】:

  • 你能告诉我们JSON文件的内容吗?
  • AJAX 一般不能用于读取本地文件。
  • 在这里找到 --> jsfiddle.net/95fktyg8
  • 那我可以用什么来读取本地文件呢?
  • 如果你使用dataType: 'text',你能读取文件吗?

标签: javascript jquery json mime-types


【解决方案1】:

如果这是一个本地文件,你应该使用$.getJSON它仍然是异步的。

$.getJSON("json/local_json_file.json", function(json) {
     //do stuff to the json object here
});

【讨论】:

  • $.getJSON 只是$.ajaxdataType: 'json' 的快捷方式。它们最终都使用相同的 jQuery 代码来执行 AJAX 请求。
  • 我用过,但遇到了同样的问题。
  • 好吧有道理!为了以后的读者,我会留下答案,您的评论很有帮助
猜你喜欢
  • 1970-01-01
  • 2010-10-15
  • 2014-11-03
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多