簡體   English   中英

Javascript:在計算機和本地服務器上運行時的行為不同

[英]Javascript : Different behavior when run on machine and local server

因為標題太短,所以我將解釋得更清楚。 我已經在JavaScript中創建了代碼。 我有兩個選擇可以運行:

1)在計算機上運行:只需單擊進入html文件。

2)在本地服務器上運行:表示我啟動Apache,並在localhost中啟動此html文件。

(例如, http://localhost:85/Javascript/index.html

當我選擇解決方案1時,什么都不會發生。 當我選擇解決方案2時,就如我所願。 但是我不知道為什么。

這是我的代碼。 目的:獲取一個json文件並對其進行處理。

<script>
        window.onload = function(){
            var url = "http://localhost:85/javascript/json1.json";  // problem here
            var request = new XMLHttpRequest();
            request.open("GET", url);
            request.onload = function(){
                if (request.status == 200){
                    update(request.responseText);
                }
            }
            request.send(null);
        };
function update(responseText){ // some code here }
</script>

您不能使用AJAX從其他域讀取內容。

file://whatever運行的Javascript無法讀取localhost:85

您是否用服務器的原始路徑替換了此行?

var url = "http://localhost:85/javascript/json1.json";

var url = "http://10.0.0.X:85/javascript/json1.json"; // Did you change the right path?

並確保未使用file://協議調用該頁面!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM