[英]Need help on how to Http Get request in Javascript
I need to call the API to get the data. 我需要调用API来获取数据。 Here is the current implementation. 这是当前的实现。
return $.get(API_URL)
.then(function (response) {
return response.data;
}, function (response) {
return response.data;
});
And when i console log value of the response. 并且当我控制台响应的日志值时。 Have this. 有这个。
console.log(response.data);
Output: [object Object]
When I check the Network->Response: 当我检查网络->响应时:
JSON
Data
0: Object
1: Object
Success: True
I need to count the number of object in the response. 我需要计算响应中对象的数量。 What should I do? 我该怎么办?
var responseData = JSON.parse(response.data.data)
this should give you an object with actual data 这应该给你一个带有实际数据的对象
and then to count properties of that object with just vanilla JS (this is a lot easier if you use libs or frameworks with stuff like for each etc) 然后仅使用普通JS来计算该对象的属性(如果您将libs或框架与类似的东西一起使用,则这样会容易得多)
if (!Object.keys) {
Object.keys = function (obj) {
var keys = [],
k;
for (k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
keys.push(k);
}
}
return keys;
};
}
var numberOfProperties= Object.keys(obj).length;
Or in ES5 compatible environment you could use: 或者在与ES5兼容的环境中,您可以使用:
Object.keys(obj).length
You could use jQuerys getJSON or explicietly tell that you want to receive something of the content type application/json (jQuery already tries to guess the type so this is should not be necessary). 您可以使用jQuerys getJSON或明确告诉您要接收内容类型application / json的内容(jQuery已经尝试猜测该类型,因此这不是必需的)。 To get the Object values, regardless of their key values, do this: 要获取对象值,无论其键值如何,请执行以下操作:
function getMyObjects(){
return $.getJSON(API_URL)
.then(function processMyData(data) {
// if data is an Object with only indices as keys:
return Object.values(data);
})
.catch(console.log);
}
This will give you an Array where you can just use the length property 这将为您提供一个数组,您可以在其中使用length属性
getMyObjects()
.then(function(theArray){
console.log(theArray.length);
})
.catch(console.log);
If you want to do something with the keys, you can use 如果您想对按键进行操作,可以使用
Object.keys(data).forEach(function(key){console.log(key, data[key])});
If you have to work with old browsers and without some polyfilling, use a for-in
-loop, see here 如果您必须使用旧的浏览器并且没有进行某些填充,请使用for-in
loop,请参见此处
More about jQuerys getJSON here 有关jQuerys getJSON的更多信息,请点击此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.