[英]get Object inside array javascript
I am struggling to get json object outside XMLHttpRequest
.This is what I did:我正在努力在 XMLHttpRequest 之外获得XMLHttpRequest
。这就是我所做的:
var ohl_json=[];
var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', 'https://raw.githubusercontent.com/tekija/LCd/master/testSO.json', true);
req.onload = function() {
var jsonResponse = req.response;
ohl_json.push(jsonResponse)
};
req.send();
console.log(ohl_json)
I get following output:我得到以下 output:
Array []
0: Object { type: "FeatureCollection", features: (960) […] }
features: Array(960) [ {…}, {…}, {…}, … ]
type: "FeatureCollection"
<prototype>: Object { … }
length: 1
<prototype>: Array []
I tried to reference it with ohl_json[0]
or ohl_json.features
but no success.我试图用ohl_json[0]
或ohl_json.features
来引用它,但没有成功。 How can I access it?我怎样才能访问它? Any help is appreciated.任何帮助表示赞赏。
A better way to do this:一个更好的方法来做到这一点:
async function getData(){
const data = await (await fetch('https://raw.githubusercontent.com/tekija/LCd/master/testSO.json')).json()
console.log(data.features)
};
getData();
Doing this, you will acess the features object =)这样做,您将访问功能 object =)
In your code snippet, you have set the 3rd parameter of req.open
as true
which means it will work asynchronously.在您的代码片段中,您已将req.open
的第三个参数设置为true
,这意味着它将异步工作。
req.open('GET', 'https://raw.githubusercontent.com/tekija/LCd/master/testSO.json', true);
If you wrap your XMLHttpRequest into a promise and resolve with the response then you would be able to get the JSON outside the function. If you wrap your XMLHttpRequest into a promise and resolve with the response then you would be able to get the JSON outside the function.
function getResponse() { return new Promise(function (resolve, reject) { const req = new XMLHttpRequest(); req.responseType = 'json'; req.open('GET', 'https://raw.githubusercontent.com/tekija/LCd/master/testSO.json', true); // Third parameter is true which means request will work asyncronously. req.onload = function() { resolve(req.response); }; req.send(); }); } getResponse().then(function(res) { console.log(res.features); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.