Hello everyone I'm trying to display some data when I make an HTTPRequest but when I call the function that retrieves a callback from the httprequets the scope of the function wont let me get to the data I want to display so I have to repeate code Im trying to find the best solution to not have to repeate same code sentences. TY in advance.
function loadJSON(callback) {
var stringQuery = decodeURIComponent(window.location.search.replace(/^.*?\=/, ''));
var xobj = new XMLHttpRequest();
xobj.open('GET', 'http://localhost:3000/data/?email='+stringQuery, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
};
xobj.send(null);
};
function gettingReportbyEmail(){
var stringQuery = decodeURIComponent(window.location.search.replace(/^.*?\=/, ''));
var datos = {};
var datos = JSON.parse(localStorage.getItem(stringQuery));
if (datos == null) {
loadJSON(function(response){
localStorage.setItem(stringQuery, JSON.stringify(response[0]));
var datos = {}; //This is where I have to repeate same code as above
var datos = JSON.parse(localStorage.getItem(stringQuery));
displayEmailandRelatives(datos);
});
}else{
datos = JSON.parse(localStorage.getItem(stringQuery));
}
};
no errors just trying to find a better solution.
if (datos == null) {
loadJSON(function(response){
localStorage.setItem(stringQuery, JSON.stringify(response[0]));
datos = response[0];
displayEmailandRelatives(datos);
});
}
I don't see any purpose of setting the value to localStorage and reading the same value just to call a function.
simply remove the duplicated code and it should work
function gettingReportbyEmail(){
var stringQuery = decodeURIComponent(window.location.search.replace(/^.*?\=/, ''));
// remove the code
if (datos == null) {
loadJSON(function(response){
localStorage.setItem(stringQuery, JSON.stringify(response[0]));
displayEmailandRelatives(datos);
});
}else{
datos = JSON.parse(localStorage.getItem(stringQuery));
}
};
it should work because of JavaScript Closures https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
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.