改善js范围的最佳方法

时间:2019-07-04 06:14:09

标签: javascript xmlhttprequest

大家好,我尝试发送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)); 
    }
  };

尝试找到更好的解决方案没有错误。

2 个答案:

答案 0 :(得分:0)

public class OrderVM
{
    public OrderVM() 
   { 
        Bicycles = new List<BicycleVM>(); //add this line
    }

    public OrderVM(OrderDTO row)
    {
        Id = row.Id;
        ClientId = row.ClientId;
        OrderDate = row.OrderDate;
        Bicycles = new List<BicycleVM>();
    }

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

答案 1 :(得分:0)

只需删除重复的代码,它应该可以工作

for timestamp, values in j1['Time Series (5min)'].items():
    print(timestamp, values['1. open'])

它应该工作,因为JavaScript处于关闭状态 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures