The error I got from my browser is this:
Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
I put the pics in my github and the json file. I am executing the html file from my workstation. Should I push the html file to github and execute it from there?
This is my Json file pushed to my Github.
{
"events" : [
{ "location" : "San Francisco, CA", "date" : "May 1", "img" :"pic1.jpg"},
{ "location" : "Austin , TX", "date" : "May 15", "img" :"pic2.jpg"},
{ "location" : "New York , NY", "date" : "May 30", "img" :"pic3.jpg"}
]
}
This is my HTML file:
<!DOCTYPE html>
<html>
<body>
<h2>User Account Example</h2>
<script>
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.open("GET", 'https://github.com/${username}/JSON/myjson.json', true);
xhr.send(null);
xhr.onload = function () {
console.log("xhr.status: " + xhr.status);
if (xhr.status === 200) {
console.log("Pineapple Juice");
responseObj = JSON.parse(xhr.responseText);
var newContent = '';
var i;
for (i = 0; i < responseObj.events.length; i++) {
newContent += '<div class="event">';
newContent += '<img src="' + responseObj[i].img + '"';
newContent += 'alt="' + responseObj[i].location + '" />';
newContent += '<p><b>' + responseObj[i].location + '</b><br>';
newContent += responseObj.events[i].date + '</p>';
newContent += '</div>';
}
document.getElementById("myuser").innerHTML = newContent;
}
};
</script>
<div id="myuser"></div>
</body>
</html>
The order is wrong. And Access-Control-Allow-Origin
is a response header, this not for requests. Furthermore GET requests cannot have a body, so you don't need the content-type header.
var xhr = new XMLHttpRequest();
xhr.onload = function () {
console.log("xhr.status: " + xhr.status);
if (xhr.status === 200) {
console.log("Pineapple Juice");
responseObj = JSON.parse(xhr.responseText);
var newContent = '';
var i;
for (i = 0; i < responseObj.events.length; i++) {
newContent += '<div class="event">';
newContent += '<img src="' + responseObj[i].img + '"';
newContent += 'alt="' + responseObj[i].location + '" />';
newContent += '<p><b>' + responseObj[i].location + '</b><br>';
newContent += responseObj.events[i].date + '</p>';
newContent += '</div>';
}
document.getElementById("myuser").innerHTML = newContent;
}
};
xhr.open("GET", `https://github.com/${username}/JSON/myjson.json`, true);
// here can you set request headers
xhr.setRequestHeader("Accept", "application/json");
xhr.send(null);
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.