首页 > 解决方案 > 改进 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)); 
    }
  };

没有错误只是试图找到更好的解决方案。

标签: javascriptxmlhttprequest

解决方案


 if (datos == null) {
      loadJSON(function(response){
      localStorage.setItem(stringQuery, JSON.stringify(response[0]));
      datos = response[0];
      displayEmailandRelatives(datos);
      });  
    }

我看不到将值设置为 localStorage 并读取相同值只是为了调用函数的任何目的。


推荐阅读