javascript - 改进 js 作用域的最佳方法
问题描述
大家好,我在发出 HTTPRequest 时试图显示一些数据,但是当我调用从 httprequets 检索回调的函数时,函数的范围不会让我访问我想要显示的数据,所以我必须重复代码我试图找到不必重复相同代码句子的最佳解决方案。提前 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));
}
};
没有错误只是试图找到更好的解决方案。
解决方案
if (datos == null) {
loadJSON(function(response){
localStorage.setItem(stringQuery, JSON.stringify(response[0]));
datos = response[0];
displayEmailandRelatives(datos);
});
}
我看不到将值设置为 localStorage 并读取相同值只是为了调用函数的任何目的。
推荐阅读
- c++ - ifstream getline - 将 txt 文件读取到对象数组,但它只读取第一行?
- python - .py 和 .kv 的 Kivy 问题
- node.js - 让未解析的异步函数在 nodejs 服务器上执行
- c++ - c++程序打印出地址而不是值
- youtube - Silverstripe 3:覆盖 TinyMCE 样式
- python - 没有循环的迭代二项式更新
- mysql - 访问数据 MySQL。冻结构建
- python - python中键盘模块的奇怪错误
- r - OpenMP、随机变量和再现性
- python - scikit 中 log_loss 的行为与 numpy 数组相比