I have an external resource similar to https://www.googleapis.com/freebase/v1/text/en/bob_dylan which returns a JSON. I want to display the value of result key in a div in html (lets say the name of the div is "summary"). Also the value of result key should be displayed in plain text.
The URL returns the json:
{ "result": "Bob Dylan, born Robert Allen Zimmerman, is an American singer-songwriter, author, poet, and painter, who has been a major figure in popular music for five decades. Much of Dylan's most celebrated work dates from the 1960s, when he became an ......." }
The JSON has just the result key, no other keys
Basically I do not want to use anything other than plain HTML and JavaScript. I am a relative beginner to JavaScript and therefore I ask for commented code.
Get JSON From URL Using jQuerygetJSON(url, data, success) is the signature method for getting JSON from an URL. In this case, the URL is a string that ensures the exact location of data, and data is just an object sent to the server. And if the request gets succeeded, the status comes through the success .
Here is one without using JQuery with pure JavaScript. I used javascript promises and XMLHttpRequest You can try it here on this fiddle
HTML
<div id="result" style="color:red"></div>
JavaScript
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('https://www.googleapis.com/freebase/v1/text/en/bob_dylan').then(function(data) { alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug result.innerText = data.result; //display the result in an HTML element }, function(status) { //error detection.... alert('Something went wrong.'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With