简体   繁体   English

如何使用.getjson获取json

[英]How to get json using .getjson

I have an endpoint https://api.iextrading.com/1.0/tops?symbols=aapl but when I try to use .getjson with that url I get a 404 error. 我有一个端点https://api.iextrading.com/1.0/tops?symbols=aapl,但是当我尝试对该网址使用.getjson时,出现404错误。 In the api documentation it mentions that it may be a jsonp request and if so how do I get .getjson to be able to read this call. 在api文档中,它提到这可能是一个jsonp请求,如果是这样,我如何获取.getjson才能读取此调用。 Thank you in advance. 先感谢您。

The code I have tried is... 我尝试过的代码是...

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> </head> <body> <h2>Create Object from JSON String</h2> <p id="demo"></p> <script> $.getJSON('https://api.iextrading.com/1.0/stock/tsla', function(data) { var obj = JSON.parse(data); document.getElementById("demo").innerHTML = obj.id; }); </script> </body> </html> 

The API or remote resource must set the header. API或远程资源必须设置标头。 You can try 你可以试试

function(xhr) {
    xhr.setRequestHeader('X-Test-Header', 'test-value');
}

The URL you are using doesn't match your description's URL, and the URL actually returns a 404. 您使用的网址与您的说明的网址不匹配,并且该网址实际上返回了404。

Using your description's URL works, however getJSON parses the data so we don't need to do JSON.parse(data); 使用您描述的URL是getJSON ,但是getJSON解析数据,因此我们无需执行JSON.parse(data); .

Finally, your data doesn't actually have a id attribute so that will return undefined. 最后,您的数据实际上没有id属性,因此将返回undefined。

I have changed it to symbol which returns AAPL. 我将其更改为返回AAPL的symbol

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> </head> <body> <h2>Create Object from JSON String</h2> <p id="demo"></p> <script> $.getJSON('https://api.iextrading.com/1.0/tops?symbols=aapl', function(data) { var obj = data[0]; document.getElementById("demo").innerHTML = obj.symbol; }); </script> </body> </html> 

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

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