Need Help Reading JSON object from a URL in a HTML -
i trying create website in can particular json object url , display on website. field trying display uv_index out of 3 fields. nothing being printed out. don't know if getting json object.
<!doctype html> <html> <body> <h2>epa </h2> <p id="demo"></p> <script> var getjson = function(url) { return new promise(function(resolve, reject) { var xhr = new xmlhttprequest(); xhr.open('get', url, true); xhr.responsetype = 'json'; xhr.onload = function() { var status = xhr.status; if (status == 200) { resolve(xhr.response); } else { reject(status); } }; xhr.send(); }); }; getjson('http://iaspub.epa.gov/enviro/efservice/getenvirofactsuvdaily/zip/92507/json').then(function(data) { document.getelementbyid('uv_index').innerhtml=json.result; alert('your json result is: ' + json.result); //you can comment this, used debug result.innertext = data.result; //display result in html element }, function(status) { //error detection.... alert('something went wrong.'); }); </script> </body> </html>
i added third-party chrome extenstion cors issue. error
uncaught (in promise) referenceerror: json not definedmessage: "json not defined"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: error
you can try using ajax plugin make cors request cors headers not being served service.
add jquery library , add installed cors ajax scripts after that:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="js/jquery.ajax-cross-origin.min.js"></script>
now can make cross origin request adding crossorigin: true in ajax: e.g.
$.ajax({ crossorigin: true, url: "http://iaspub.epa.gov/enviro/efservice/getenvirofactsuvdaily/zip/92507/json/", success: function(data) { console.log(data); } });
you can try putting same url in below demo page receive json data. see live demo.
Comments
Post a Comment