【问题标题】:Javascript - getJSON to fetch data from local fileJavascript - getJSON 从本地文件中获取数据
【发布时间】:2017-03-10 15:30:15
【问题描述】:

我有一个包含在本地 Json 文件中的数据结构。我想使用$.getJSON() 加载它。

json文件locations.json

{locations:
    [{value: "Port Kelang",label: "Port Kelang",category: "Malaysia"},
     {value: "Pusan",label: "Pusan",category: "South Corea"},
     {value: "Qingdao",label: "Qingdao",category: "China"}]}

javascript 文件:

    $.getJSON("locations.json", function(data){
          //do something
    });

使用 Chrome 时出现错误:

XMLHttpRequest cannot load file:///E:/locations.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

虽然我在 Firefox 中遇到了另一个错误:

XML Parsing Error: not well-formed Location: file:///E:/locations.json Line Number 1, Column 1:

有什么帮助吗?提前致谢。

【问题讨论】:

  • 通过另一台服务器托管这些文件。 ftp 可能吗?
  • 如果您阅读 Chrome 的错误消息,它会告诉您出了什么问题。此外,正如 Firefox 告诉您的那样,您的 JSON 格式不正确。必须引用属性名称。见json.org
  • @MikeMcCaughan 实际上,即使引用了属性名称,我在 Firefox 中也遇到了同样的错误。
  • ...那么您的 JSON 有其他问题。使用像 jsonlint.com 这样的 linting 工具来确保你的 JSON 是 JSON。

标签: javascript jquery json getjson


【解决方案1】:

出于安全原因,浏览器不允许跨源请求。我在本地开发时遇到了这个问题。这是您在远程服务器上不会遇到的问题。 我做了什么,我在浏览器中禁用了同源策略: 如果你在 mac 上执行:

 open -a Google\ Chrome --args --disable-web-security -–allow-file-access-from-files

如果你在窗口,这个:

"C:\PathTo\Chrome.exe" –allow-file-access-from-files -disable-web-security

【讨论】:

    猜你喜欢
    • 2018-10-24
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多