XMLHttpRequest is not working for Json

1.3k views Asked by At

Am very new to JSON. So read some topics on w3schools and tried to execute locally but its not working. Kindly anyone help me to overcome this issue.

Note: 1) Kept 1.html and myTutorials.txt files in same directory. 2) I debugged the html code and found that "xmlhttp.status" is always zero. 3) But same code in w3schools website is working fine. Links:

i) http://www.w3schools.com/json/json_http.asp --> 1.html
ii) http://www.w3schools.com/json/myTutorials.txt --> myTutorials.txt

My Html code: 1.html

<!DOCTYPE html>
<html>
<body>

<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + 
        arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}
</script>

</body>
</html>


The below contents are from "myTutorials.txt" file.

[
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
},
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "jQuery Tutorial",
"url": "http://www.w3schools.com/jquery/default.asp"
},
{
"display": "JSON Tutorial",
"url": "http://www.w3schools.com/json/default.asp"
},
{
"display": "AJAX Tutorial",
"url": "http://www.w3schools.com/ajax/default.asp"
},
{
"display": "SQL Tutorial",
"url": "http://www.w3schools.com/sql/default.asp"
},
{
"display": "PHP Tutorial",
"url": "http://www.w3schools.com/php/default.asp"
},
{
"display": "XML Tutorial",
"url": "http://www.w3schools.com/xml/default.asp"
}
]


1

There are 1 answers

0
user2466202 On

The reason XMLHttpRequest doesn't work because you're using file:// protocol to open the html file. The XMLHttpRequest object is used to exchange data with a server behind the scenes. When trying to do a HTTP request using XMLHttpRequest from a local file, it basically fails due to Access-Control-Allow-Origin violation. So what you need to do is to host the html file and text file in a web server and then access the html file using http protocol i.e. enter the url of html page in web browser like: http://www.example.com/1.html.