javascript - Code is not displaying JSON data -
hey guys trying make request json page, grabbing data, displaying console giving me "undefined". why that?
here code , json page posted under it:
(function apod() { var api_key = 'nnkojkoul8n1ch1noufo', url = 'https://api.nasa.gov/planetary/apod' + "?api_key=" + api_key, data; var apodrequest = new xmlhttprequest(); apodrequest.onreadystatechange = function() { if (apodrequest.readystate === 4 && apodrequest.status === 200) { var response = apodrequest.responsetext; var parsedapod = json.parse(response); data += parsedapod; (i = 0; < parsedapod.length; i++) { data += parsedapod[i]; console.log("parsing lines: <br>" + parsedapod[i]); } } apodrequest.open("get", url, true); apodrequest.send(null); } }());
json page parsing:
{ "date": "2016-11-05", "explanation": "shot in ultra hd, stunning video can take on tour of international space station. fisheye lens sharp focus , extreme depth of field provides immersive visual experience of life in orbital outpost. in 18 minute fly-through, point of view float serenely while watch our fair planet go 400 kilometers below seven-windowed cupola, , explore interior of station's habitable nodes , modules astronaut's perspective. modular international space station earth's largest artificial satellite, size of football field in overall length , width. total pressurized volume approximately equal of boeing 747 aircraft.", "media_type": "video", "service_version": "v1", "title": "iss fisheye fly-through", "url": "https://www.youtube.com/embed/dhmdyqdu96m?rel=0" }
you have few errors in code.
first off, general structure of should this
(function apod() { var api_key = 'nnkojkoul8n1ch1noufo', url = 'https://api.nasa.gov/planetary/apod' + "?api_key=" + api_key, data; var apodrequest = new xmlhttprequest(); apodrequest.onreadystatechange = function() { //code here }; apodrequest.open("get", url, true); apodrequest.send(null); }());
notice how moved apodrequest.open("get", url, true);
, apodrequest.send(null);
outside of onreadystatechange
handler.
secondly, instead of
apodrequest.onreadystatechange = function() { if (apodrequest.readystate === 4 && apodrequest.status === 200) { //code here } }
you can
apodrequest.onload = function() { //code here };
as it's event fire when response returned. don't need if
check inside.
finally, inside onload
handler, have few mistakes, such as:
data += parsedapod;
wrong becausedata
objectundefined
point ,parsedapod
object.doing+=
between 2 objects not merge them. if want merge 2 objects there other ways, e.g.object.assign
for (i = 0; < parsedapod.length; i++) { ... }
wrong becauseparsedapod
object. objects not havelength
property, not correct way iterate on it. usefor ... in ...
loop insteaddata += parsedapod[i];
is, again, wrong, because not way merge objects.parsedapod[i]
wrong becausei
integer, in case,parsedapod[i]
undefined.
hope analysis helps correct code.
Comments
Post a Comment