JSON字符串未将数据加载到本地存储中

时间:2018-07-28 20:22:42

标签: javascript html json

我正在构建一个应用程序,该应用程序会将公交时刻表加载到本地存储中,然后根据搜索字词提供公交时刻表的停靠点。通过单击“加载”按钮并将信息发送到本地存储,它可以工作。然后搜索路线名称,站点信息将显示在结果中。当我在浏览器中运行时,按“加载”时,数据不会加载到本地存储中。

<html>
<head>
<script type="text/javascript">

/**
 * A JSON string that holds data. There is no problem with the JSON string
 * @type {String}
  */

    var busSchd = '{"Routes": [{"routeName": "Milledge","stops":[{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}]},{"routeName": "Orbit","stops":[{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}]},{"routeName": "East West","stops":[{"Stop 1":"East Campus Deck","Stop 2":"Creswell Hall","Stop 3":"Hull St Deck","Stop 4":"Main Library","Stop 5":"Joe Frank Harris"}]}]}';

    
const load = () => {
    let data = JSON.parse(busSchd);
    console.log("a");
for (var i = 0; i < data.Routes.len;)
     {
         let route = data.Routes[i];
         let routeStr = route.routeName;
         localStorage.set(routeStr, JSON.stringify(route.stops));
      }

};

    const clicked = () => {
     
       var search = document.getElementById("search");
       var results = localStorage.getItem("search");

      if (results === null) {
        document.getElementById("result").innerHTML = "<b>There are no results for that route name.</b>";
      } else {
        var stops = results;
        var output = '';
        for (var key in stops[0]) {
          output = output + '<b>' + key + '</b> : ' + stops[0][key] + '<br>';
        }
        document.getElementById("result").innerHTML = output;
      }
    };
  </script>
</head>
<body>
  <input type="button" value="Load Route Data" id="load" onclick="load();">
  <br>
  <br>
  <input type="text" id="search"><input type="button" value="Find Route" id="submit" onclick="clicked();"><br>
  <br><br>
  <div id="result">
  </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误,导致您无法保存到localStorage。这里有一些指针。

  • 使用localStorage.setItem()保存并使用localStorage.getItem()检索数据。
  • 无需为每个公交路线创建localStorage项。 LocalStorage可以处理很多数据,具体取决于浏览器和用户浏览器设置。有关更多信息,请参见What is the max size of localStorage values?
  • 我会简化您的数据结构。为什么将停止数据放入数组然后放入对象?我在示例中对此进行了简化。
  • 当迭代项时使用for (var i = 0; i < data.Routes.length; i++) { // your code here },另一种替代方法是当迭代数组中的项时使用用户.map

这里是加载数据并将其保存到localStorage以及应用程序中的方法。

let BusSchdDataFromLocalStorage = [];

const load = () => {
  // access localStorage and save the result in data 
  let data = JSON.parse(localStorage.getItem('routesInfo'));
  if (data === null) {
    // if no data is present, save InitialBusScheduleData to localStorage
    localStorage.setItem('routesInfo', JSON.stringify(InitialBusScheduleData));
  }

  // Now that data is present in localStorage, read it.
  data = JSON.parse(localStorage.getItem('routesInfo'));
  if (data.Routes.length > 0) {
    // if routes are present, save its data to a global var in our app
    BusSchdDataFromLocalStorage = data;
    statusEl.innerHTML = 'localStorage data present'
  } else {
    statusEl.innerHTML = 'localStorage data absent'
  }
};

这是搜索部分的工作方式。

const search = () => {
  const searchString = document.querySelector('#search').value;
  // data from localStorage is present in the variable below 
  const routes = BusSchdDataFromLocalStorage.Routes;

  // Filter route data based on the search input. 
  const busStopInfo = routes.reduce((stops, route) => {
    return (route.routeName.toLowerCase() === searchString.toLowerCase()) ? route.stops : stops;
  }, []);
  const stops = Object.keys(busStopInfo);
  // map over the stops and return the html structure with the stop number and the value
  const results = stops
    .map((stop) => '<div>' + stop + ' - ' + busStopInfo[stop] + '</div>')
    .join('');
  // add the html result to the result div.
  resultEl.innerHTML = results.length > 0 ? results : 'No route found with that name.';
};

如果您想查看运行中的代码。 Here's a JSFiddle