[英]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.对于我的项目,我一直在尝试通过 URL 读取 Json 数据并将其显示在网页上。 I want to use only Javascript.我只想使用 Javascript。
Im new to this.我对此很陌生。 Help me out by reading JSON data from this link:通过从此链接读取 JSON 数据来帮助我:
http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo 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.我做了一些研究后尝试使用 AJAX。 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:使用 XMLHttpRequest,例如:
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:您可以使用基于 Promise 的库,例如 axios:
add library <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
添加库<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 和外部资源时,请确保您使用的是 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 .来自 JQuery 的示例和SO Example 。 Also a nice article on JSONP .也是一篇关于 JSONP的好文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.