在 Chrome 中使用本地文件的 jQuery getJSON 问题

问题描述 投票:0回答:7

我有一个非常简单的测试页面,它使用带有 jQuery 的 $.getJSON 和 $.ajax 方法的 XHR 请求。同一页面在某些情况下有效,但在其他情况下则无效。具体来说,它在 Ubuntu 上的 Chrome 中不起作用。

我正在使用 Chrome 5.0.342.7 beta 的 Ubuntu 9.10 和使用 Chrome 5.0.307.9 beta 的 Mac OSX 10.6.2 上进行测试。

  • 当文件从 Ubuntu/Chrome 和 Mac/Chrome 安装到 Web 服务器上时,它可以正常工作(在此处尝试一下)。
  • 当文件安装在 Mac/Chrome 的本地硬盘上时(通过 file:///... 访问),它可以正常工作。
  • 在 Ubuntu/Chrome 中将文件安装到本地硬盘上时失败(使用 file:///... 访问)。

可以从此处下载 tar/gzip 文件中的一小组 3 个文件: http://issues.tauren.com/testjson/testjson.tgz

运行时,Chrome 控制台会显示:

XHR finished loading: "http://issues.tauren.com/testjson/data.json".
index.html:16Using getJSON
index.html:21
Object
result: "success"
__proto__: Object
index.html:22success
XHR finished loading: "http://issues.tauren.com/testjson/data.json".
index.html:29Using ajax with json dataType
index.html:34
Object
result: "success"
__proto__: Object
index.html:35success
XHR finished loading: "http://issues.tauren.com/testjson/data.json".
index.html:46Using ajax with text dataType
index.html:51{"result":"success"}
index.html:52undefined

当它不起作用时,Chrome 控制台会显示以下内容:

index.html:16Using getJSON
index.html:21null
index.html:22Uncaught TypeError: Cannot read property 'result' of null
index.html:29Using ajax with json dataType
index.html:34null
index.html:35Uncaught TypeError: Cannot read property 'result' of null
index.html:46Using ajax with text dataType
index.html:51
index.html:52undefined

请注意,尽管成功处理程序已运行,但它甚至不显示 XHR 请求。我发誓这之前在 Ubuntu/Chrome 中可以正常工作,并且担心出现问题。我已经卸载并重新安装了 Chrome,但这没有帮助。

有人可以在你的 Ubuntu 系统上本地尝试一下,并告诉我是否有任何问题吗?请注意,它在 Firefox 中似乎运行良好。

ajax json jquery google-chrome
7个回答
38
投票

另一种方法是在您的目录上启动本地 HTTP 服务器。在安装了 Python 的 Ubuntu 和 MacO 上,这是一句简单的话。

转到包含 Web 文件的目录,然后:

python -m SimpleHTTPServer

然后使用任何网络浏览器连接到 http://localhost:8000/index.html 来测试您的页面。


30
投票

这是 Chrome 的一个已知问题。

这是错误跟踪器中的链接:

问题 40787:本地文件无法使用 Ajax 加载


14
投票

在 Windows 上,Chrome 可能安装在您的 AppData 文件夹中:

“C:\Users\AppData\Local\Google\Chrome\Application”

在执行命令之前,请确保所有 Chrome 窗口均已关闭且未以其他方式运行。否则,命令行参数将不起作用。

chrome.exe --allow-file-access-from-files

3
投票

您可以将 json 放入 js 文件并将其保存到全局变量中。它不是异步的,但它可以提供帮助。


1
投票

解决该问题的另一种方法是利用 Flash Player 的 Local Only 安全沙箱和ExternalInterface 方法。可以让 JavaScript 请求使用 Local Only 安全沙箱发布的 Flash 应用程序,以从硬盘驱动器加载文件,并且 Flash 可以通过 Flash 的ExternalInterface 类将数据传递回 JavaScript。我已经在 Chrome、FF 和 IE9 中对此进行了测试,效果很好。如果有人感兴趣,我很乐意分享代码。

编辑:我已经启动了一个谷歌代码(讽刺?)项目来实现:http://code.google.com/p/flash-loader/


1
投票

@Mike 在 Mac 上,在终端中输入:

open -b com.google.chrome --args --disable-web-security

1
投票

此代码在本地与

sheet.json
配合使用浏览器同步作为本地服务器运行良好。但是在我的远程服务器上,我使用 Chrome 得到了
sheet.json
文件的 404 错误。它在 Safari 和 Firefox 中运行良好。 将名称
sheet.json
更改为
sheet.JSON
。然后就可以在远程服务器上运行了。

getthejason = function(){
var dataurl = 'data/sheet.JSON';
var xhr = new XMLHttpRequest();
xhr.open('GET', dataurl, true);
xhr.responseType = 'text';
xhr.send();
console.log('getthejason!');

xhr.onload = function() {
.....
}
© www.soinside.com 2019 - 2024. All rights reserved.