我能够遍历一个简单的json循环,但实际上我正在使用的API返回一个带有多个标题的响应,我尝试了不同的方法来访问results
个对象,但仍然无法正常工作,响应如下:
"meta": { "name": "openaq-api", "license": "CC BY 4.0", "website": "https://docs.openaq.org/", "page": 1, "limit": 100, "found": 1544 }, "results": [ { "city": "Buenos Aires", "country": "AR", "locations": 4, "count": 8064 }, { "city": "Gemeinde Wien, MA22 Umweltschutz", "country": "AT", "locations": 21, "count": 136958 },
我要做的是访问结果然后使用城市信息迭代,我的可运行尝试:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
<title>Open AQ API</title></head>
<body>
<div id="data"></div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script type="text/javascript">
var url = "https://api.openaq.org/v1/cities";
$.getJSON(url, function (data) {
var json = data
$.each($.parseJSON(json), function() {
alert(results.this.city);
});
});
</script>
</body>
</html>
尝试2:
// data[i]
$.each(data, function(i, item){
$('#data').append(
$('<h1>').text(item.results.city),
$('<div>').text(item.results.country),
$('<h6>').text(data[i].results.count),
);
});
答案 0 :(得分:1)
这很好用,试试这个jQuery。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
<title>Open AQ API</title></head>
<body>
<div id="data"></div>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script type="text/javascript">
var url = "https://api.openaq.org/v1/cities";
$.getJSON(url, function (data) {
$.each(data.results, function(i, result) {
console.log(result.city);
});
});
</script>
</body>
</html>
答案 1 :(得分:0)
请更新以下逻辑,数据将给出完整响应,因此您必须从$ .parseJSON(json).results等数据中获取结果,然后针对每个循环运行,如下所示。
$.each(json.results, function(index,value) {// json is same as data as per your code
alert(value.city);
});