简体   繁体   English

使用JavaScript读取从REST API返回的JSON数据

[英]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. 以下代码应该只是向我发出我希望从JSON文件中获取的值的警报。 The problem is it doesn't give me anything back :(. Below is the link for the JSON file: 问题是它没有给我任何回报:(.。下面是JSON文件的链接:

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. 如果您不知道, Soil Grids API是一种API,用于为您提供有关土地质量的特定纬度和经度的土壤信息。

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... 每当程序运行时,我都会收到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 ). 问题是没有REST方法( 请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open )。

Using GET works. 使用GET

 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. 这样,您就可以通过检查ready状态属性来对结果进行处理。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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