You have several methods of doing so.
Define the variable outside of the function:
var teacherIDList;
function doXHR() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
teacherIDList = eval("(" + this.responseText+ ")");
}
}
However, with this method, you don't know when the XHR will complete and teacherIDList
is populated. This might be ok depending on how you're using the variable, but a much better way is to use a promise:
Use a promise:
function doXHRPromise() {
return new Promise(function(resolve, reject) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
}
}
}
...
}
doXHRPromise.then(function(responseText) {
var teacherIDList = eval("(" + this.responseText+ ")");
// do whatever else you need to do here
});
This way you can ensure that teacherIDList
is populated before acting on it.
P.S. Do NOT use eval()
, you're opening yourself up to cross-site scripting attacks.
See this link for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval