[英]Console.log statement is showing undefined when logging an AJAX/ JSON request
This is the first time I've used AJAX, I am sure that other people have had this error but after lots of trying and searching I cannot find the answer. 这是我第一次使用AJAX,我敢肯定其他人也有此错误,但是经过大量尝试和搜索后,我找不到答案。 I am sure it is something simple. 我相信这很简单。 I'd appreciate any assistance. 我将不胜感激。
// create variable for JSON request
var ourRequest = new XMLHttpRequest();
// get request for tested JSON link
ourRequest.open('GET', 'http://api.fixer.io/latest');
ourRequest.onload = function () {
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData[1]);
};
ourRequest.send();
ourData
is a JavaScript object and not an array. ourData
是JavaScript对象,而不是数组。
I think by ourData[1]
you want to get the date, so instead you need to do ourData.date
or ourData['date']
我认为您要通过ourData[1]
获取日期,因此您需要执行ourData.date
或ourData['date']
// create variable for JSON request var ourRequest = new XMLHttpRequest(); // get request for tested JSON link ourRequest.open('GET', 'https://api.fixer.io/latest'); ourRequest.onload = function () { var ourData = JSON.parse(ourRequest.responseText); console.log(ourData['date']); console.log(ourData.date); }; ourRequest.send();
Since respoonse is in Json so you can use the following code and use whatever way you like 由于respoonse在Json中,因此您可以使用以下代码并按自己喜欢的方式使用
var ourRequest = new XMLHttpRequest();
// get request for tested JSON link
ourRequest.open('GET', 'http://api.fixer.io/latest');
ourRequest.onload = function () {
var ourData = JSON.parse(ourRequest.responseText);
console.log(ourData['date']);
console.log(ourData.date); //or you can write in this format
console.log(ourData['base']);
console.log(ourData.base);
console.log(ourData['rates']);
console.log(ourData.rates);
console.log(ourData['rates']['AUD']);
console.log(ourData['rates'].AUD);
};
ourRequest.send();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.