-1

For my project I've been trying to Read Json data over an URL and display it on a webpage. I want to use only Javascript.

Im new to this. Help me out by reading JSON data from this link:

http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo

I tried using AJAX after doing a bit of research. Still haven't arrived at the solution:

 $(document).ready(function () {

 $('#retrieve-resources').click(function () {
 var displayResources = $('#display-resources');

 displayResources.text('Loading data from JSON source...');

 $.ajax({
 type: "GET",
 url: "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo",
 success: function(result)
 {
 console.log(result);
 var output="<table><thead><tr><th>LNG</th><th>GEONAMEID</th><th>COUNTRYCODE</th></thead><tbody>";
 for (var i in result)
 {
 output+="<tr><td>" + result.geonames[i].lng + "</td><td>" + result.geonames[i].geonameId + "</td><td>" + result.geonames[i].countrycode + "</td></tr>";
 }
 output+="</tbody></table>";

 displayResources.html(output);
 $("table").addClass("table");
 }
 });

 });
});
  • what have you tried so far? – guradio Feb 08 '18 at 07:10
  • Where is your code ? Show us what you tried – Weedoze Feb 08 '18 at 07:11
  • Please do a minimum of research before posting here, as there are plenty of threads here and there with same questions about reading json – Pierre Feb 08 '18 at 07:15
  • Possible duplicate of [How can I get javascript code as text from .js to be inserted into an html page?](https://stackoverflow.com/questions/48606813/how-can-i-get-javascript-code-as-text-from-js-to-be-inserted-into-an-html-page) – xianshenglu Feb 08 '18 at 07:20

2 Answers2

0

use XMLHttpRequest, Ex:

function getText(){
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {

          document.getElementById("anchor").innerHTML = xhttp.responseText;
      }
  };
  xhttp.open("GET", "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo", true);
  xhttp.send();
}

getText()

you can use promise based libraries like axios:

add library <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

code (basic example):

function getText(){
  var response=axios.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo')
  document.getElementById('anchor').innerHTML(response.data)
}

getText()
Rohit Sharma
  • 465
  • 4
  • 6
0

When working with AJAX and external resources, make sure you are using JSONP.

$.ajax({
    type: "GET",
    url: "http://api.geonames.org/citiesJSON?",
    dataType: "jsonp",
    data: { .. },
    success: function( response ) {
        console.log( response );
    }
});

An example from JQuery and an SO Example. Also a nice article on JSONP.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257