繁体   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