我有以下的代碼非常簡單剛剛讀取JSON文件:相對和絕對路徑的JavaScript
<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欄(http:// localhost:8080/Html5_Test_1/data/sample.json)上直接輸入地址進行確認?如果您查看瀏覽器開發工具的網絡選項卡,它會嘗試加載哪個URL? – JJJ
是的,我已確認可以使用localhost:8080/Html5_Test_1/data/sample.json加載該文件。 – user1888243
好的,你可以在將'/ Html5_Test_1/data/sample.json''指定爲URL時檢查'GET'請求的實際內容嗎?並將此行與'data/sample.json'請求發送的行進行比較。 – raina77ow