简体   繁体   中英

Reading Json data using Javascript

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");
 }
 });

 });
});

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()

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM