【发布时间】:2013-05-29 16:11:21
【问题描述】:
我有以下非常简单的代码,它只读取一个 JSON 文件:
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSON Test</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(function()
{
alert (1);
$.getJSON('data/sample.json', function(json)
{
alert(2);
});
});
</script>
</head>
<body>
<div id="datadiv">This is the info: </div>
</body>
</html>
我在 Tomcat 服务器上加载了上述文件,并且可以使用:http://myserver.com:8080/Html5_Test_1/jsonTest.html 加载文件。上面的代码有效,并且调用了 alert(2)。但是,如果我将用于 getJSON 的路径更改为 /Html5_Test_1/data/sample.json,它将不起作用。
我认为 /Html5_Test_1/data/sample.json 是 data/sample.json 的绝对路径,应该可以。事实上,我已经尝试过 /data/sample.json、Html5_Test_1/data/sample.json,但都没有。唯一有效的路径是 data/sample.json。
谁能告诉我有什么问题?绝对路径 /Html5_Test_1/data/sample.json 在 Java 中肯定可以工作。那么,JavaScript 中绝对路径和相对路径的概念是不是有点不同?
请注意,该文件是作为服务器上的公共文件而不是本地文件系统上的文件访问的。
【问题讨论】:
-
您是否通过直接在浏览器的 URL 栏 (localhost:8080/Html5_Test_1/data/sample.json) 上输入地址进行确认?如果您查看浏览器开发工具的网络选项卡,它会尝试加载哪个 URL?
-
是的,我已经确认可以使用 localhost:8080/Html5_Test_1/data/sample.json 加载文件。
-
好的,当您指定
'/Html5_Test_1/data/sample.json'作为URL时,您可以查看GET请求的实际内容吗?并将这一行与'data/sample.json'请求发送的行进行比较。 -
是的,标题说被请求的文件是myserver.com:8080/Html5_Test_1/data/sample.json,这是正确的路径;但脚本仍然不起作用。
标签: javascript jquery relative-path absolute-path