简体   繁体   English

Javascript:在计算机和本地服务器上运行时的行为不同

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

Because my title is too short, I will explain more clearer. 因为标题太短,所以我将解释得更清楚。 I have create a code in JavaScript . 我已经在JavaScript中创建了代码。 And I have two options to run : 我有两个选择可以运行:

1) Run on machine : simple click into html file. 1)在计算机上运行:只需单击进入html文件。

2) Run on local server : mean I start Apache, and start this html file in localhost. 2)在本地服务器上运行:表示我启动Apache,并在localhost中启动此html文件。

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

When I choose solution 1, no thing happen. 当我选择解决方案1时,什么都不会发生。 And when I choose solution 2, happen as I wish. 当我选择解决方案2时,就如我所愿。 But I don't know why. 但是我不知道为什么。

Here is my code. 这是我的代码。 Purpose : take a json file and process it. 目的:获取一个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>

You cannot use AJAX to read content from a different domain. 您不能使用AJAX从其他域读取内容。

Javascript running from file://whatever cannot read localhost:85 . file://whatever运行的Javascript无法读取localhost:85

Did you replace this line with the server's original path? 您是否用服务器的原始路径替换了此行?

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

With

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

And make sure, the page is not called with the file:// protocol! 并确保未使用file://协议调用该页面!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM