简体   繁体   中英

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 . And I have two options to run :

1) Run on machine : simple click into html file.

2) Run on local server : mean I start Apache, and start this html file in localhost.

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

When I choose solution 1, no thing happen. And when I choose solution 2, happen as I wish. But I don't know why.

Here is my code. Purpose : take a json file and process it.

<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.

Javascript running from file://whatever cannot read 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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