简体   繁体   中英

Reading JSON Data returned from REST API using Javascript

The following code is supposed to simply alert me with the value that I am wishing to get from a JSON file. The problem is it doesn't give me anything back :(. Below is the link for the JSON file:

https://rest.soilgrids.org/query?lon=5.39&lat=51.57

In case you don't know, the Soil Grids API is an API used for giving you soil insight on a certain latitude and longitude of land mass.

I have to admit, I don't know what is wrong. Below is my code:

 var soil = new XMLHttpRequest(); function testFunction (){ soil.open("REST", "https://rest.soilgrids.org/query?lon=5.39&lat=51.57", false); soil.send(null); var r = JSON.parse(soil.response); var majorreal = r.properties.TAXNWRBMajor; alert(majorreal); } 
 <button onclick="testFunction()">Submit</button> 

Whenever the program is run, I get a send error with the XMLHttpRequest...

"Uncaught NetworkError: Failed to execute 'send' on
'XMLHttpRequest': Failed to load 'https://rest.soilgrids.org/query
lon=5.39&lat=51.57'.",

Any help would be appreciated ;).

The problem is that there is no REST method ( see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open ).

Using GET works.

 var soil = new XMLHttpRequest(); function testFunction (){ soil.open("GET", "https://rest.soilgrids.org/query?lon=5.39&lat=51.57", false); soil.send(null); var r = JSON.parse(soil.response); var majorreal = r.properties.TAXNWRBMajor; alert(majorreal); } 
 <button onclick="testFunction()">Submit</button> 

Also there is no reason to use synchronous calls.

A common convention is to follow the pattern below. This allows you to do something with the result when its is done by checking for the ready state property.

function testFunction (){
 var soil = new XMLHttpRequest();
    soil.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
      }
    };
   soil.open("GET", "https://rest.soilgrids.org/query?lon=5.39&lat=51.57", false);
   soil.send(null);
 }

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