I am able to pass an entire JSON object but am unable to index any information from it.
For instance the following code will put the entire JSON string as a single item in an unordered list
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Victoria Traffic</title>
</head>
<body>
<div id="placeholder"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://traffic.vicroads.vic.gov.au/maps.json') + '&callback=?', function(data){
var output = "<ul>";
output += data.contents;
output += "</ul>";
document.getElementById("placeholder").innerHTML = output;
});
</script>
</body>
</html>
However the following code will not output anything with the console saying: Cannot read property '0' of undefined.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Victoria Traffic</title>
</head>
<body>
<div id="placeholder"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://traffic.vicroads.vic.gov.au/maps.json') + '&callback=?', function(data){
var output = "<ul>";
output += data.contents.incidents[0].id;
output += "</ul>";
document.getElementById("placeholder").innerHTML = output;
});
</script>
</body>
</html>
What am I doing wrong?
data.contents
? It evidently doesn't contain a property namedincidents
. – p.s.w.g Feb 3 '14 at 22:56