[英]Best way to improve js scoping
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. 大家好,我在尝试发出HTTPRequest时试图显示一些数据,但是当我调用从httprequets检索回调的函数时,该函数的作用域无法让我获取要显示的数据,因此我必须重复代码我试图找到最好的解决方案,而不必重复相同的代码语句。 TY in advance. 提前TY。
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. 我看不到将值设置为localStorage并读取相同值只是为了调用函数的任何目的。
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 由于JavaScript闭包,它应该可以工作https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.