如何在控制台中打印我在控制台中的JSOP对象的值。当我尝试使用var countries = data.name检索国家/地区的名称时,在控制台中打印undefined。我注意到JSONP对象中的标签是数字。我想知道我是否必须使用这些数字写一条路线,但是当我尝试这样做时,它也无法工作。
var Getdata = function(data) {
console.log(data)
var countries = data.name;
console.log(countries)
}
var url = 'http://api.worldbank.org/countries/all/indicators/DT.DOD.PVLX.CD?date=2015&format=jsonp&prefix=Getdata';
var query_url = url;
console.log(query_url);
var script = document.createElement('script');
script.src = query_url;
document.getElementsByTagName('head')[0].appendChild(script);
</script>
答案 0 :(得分:0)
查看数据,
[
// this is data[0]
{
"page": 1,
"pages": 6,
"per_page": "50",
"total": 264
},
// this is data[1]
[
// this is data[1][0]
{
"indicator": {
"id": "DT.DOD.PVLX.CD",
"value": "Present value of external debt (current US$)"
},
"country": {
"id": "1A",
"value": "Arab World"
},
"value": null,
"decimal": "0",
"date": "2015"
},
// data[1][1 ... 49] below here
... etc
]
]
获取国家/地区列表
var countries = data[1].map(function(item) {
return item.country.value;
});
当然,您只获得该结果中前50个国家/地区的列表,您需要使用某个参数调用该API以获取接下来的5个页面(您有第1页的第6页) )强>
所以
http://api.worldbank.org/countries/all/indicators/DT.DOD.PVLX.CD?date=2015&format=jsonp&prefix=Getdata&page=2
http://api.worldbank.org/countries/all/indicators/DT.DOD.PVLX.CD?date=2015&format=jsonp&prefix=Getdata&page=3
http://api.worldbank.org/countries/all/indicators/DT.DOD.PVLX.CD?date=2015&format=jsonp&prefix=Getdata&page=4
http://api.worldbank.org/countries/all/indicators/DT.DOD.PVLX.CD?date=2015&format=jsonp&prefix=Getdata&page=5
http://api.worldbank.org/countries/all/indicators/DT.DOD.PVLX.CD?date=2015&format=jsonp&prefix=Getdata&page=6
还需要检索
以下是您可以检索所有国家/地区的方式
var Getdata = (function() {
var url = 'http://api.worldbank.org/countries/all/indicators/DT.DOD.PVLX.CD?date=2015&format=jsonp&prefix=Getdata';
var allCountries = [];
var callback;
return function Getdata(data) {
var hdr,
arr,
countries;
if (typeof data == 'function') {
// called by code
callback = data; // setup the callback
allCountries = [];
} else {
// called by JSONP type callback
hdr = data[0];
arr = data[1];
countries = arr.map(function(item) {
return item.country.value;
});
allCountries = allCountries.concat(countries);
}
if (!hdr || hdr.page < hdr.pages) {
// get the first (hdr is undefined) or next page
var script = document.createElement('script');
script.src = url + (hdr ? '&page=' + (hdr.page + 1) : '');
document.getElementsByTagName('head')[0].appendChild(script);
} else {
// done, callback the countries
callback(allCountries);
}
};
})();
刚刚打电话
Getdata(function(data) {
console.log(data);
});