I am currently writing some code to create a chart using data pulled from my API in JSON format, I want to parse this data into readable variable outside of the GET Request.
The GET Request only needs calling once upon loading the page, the data is then placed into a variable which I can iterate through and plot a chart using however I am having trouble simply pulling the data from the API and storing into a variable.
var dates = "empty";
function httpGetAsync(URL, dates) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
var response = JSON.parse(xmlHttp.responseText);
console.log(response);
dates = response;
}
xmlHttp.open("GET", URL, true); // true for asynchronous
xmlHttp.send(null);
}
httpGetAsync(URL, dates);
Whilst this does pull the data, I cannot send the data to the variable called dates as it does not update it, how can I do this?
You might be missing curly braces {
and }
after your if statement, not writing them will only enclose the next instruction ( in your case, assigning var response
).
Also, you don't need to pass dates
as an argument to your function
var dates = "empty";
function httpGetAsync(URL) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var response = JSON.parse(xmlHttp.responseText);
console.log(response);
dates = response;
}
}
xmlHttp.open("GET", URL, true); // true for asynchronous
xmlHttp.send(null);
}
httpGetAsync(URL);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.