I’m trying to get this JSON from my server:
[{"name":"Tie-Dye T-Shirt","type":"tie-dye","price":7.99},{"name":"Art1","type":"painting","price":13.99},{"name":"Hand-Made Bracelets","type":"braclet","price":5.99},{"name":"Pop-It","type":"pop-it","price":6.99},{"name":"Dimple","type":"dimple","price":7.99},{"name":"Stress Balls","type":"stress ball","price":3.99},{"name":"Mochis","type":"mochis","price":.50},{"name":"Snappers","type":"snapper","price":2.99},{"name":"Posters","type":"poster","price":5.99}]
…then parse and show it using this code:
var data = null
var xhttp = new XMLHttpRequest()
xhttp.onload = load
xhttp.open("GET", 'items.txt')
xhttp.send()
function load(){
data = JSON.parse(xhttp.responseText)
setHtml()
}
function setHtml(){
for (var i = 0; i < data.length; i++) {
var e = document.createElement('div')
e.innerHTML = '<h2>' + data[i].name + '</h2><h4>' + data[i].type + '</h4><p>' + data[i].price + '</p>'
document.getElementById('stuff').appendChild(e)
}
}
What I have tried:
I’ve tried alerting the type of the xhttp.responseText and xhttp.response to see if it was already parsed, it wasn’t. I also just locally defined the JSON and it worked fine. Mainly the problem is with the JSON.parse.