首页 > 解决方案 > 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>

标签: javascripthtmljson

解决方案


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

  • 用于localStorage.setItem()保存和localStorage.getItem()检索数据。
  • 无需为每条公交路线创建 localStorage 项目。LocalStorage 可以处理相当多的数据,具体取决于浏览器和用户浏览器设置。请参阅localStorage 值的最大大小是多少?了解更多信息。
  • 我会简化你的数据结构。为什么将停止数据放入数组然后放入对象?我在示例中对此进行了简化。
  • 当迭代项目时,使用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.';
};

如果您想查看实际的代码。这是一个 JSFiddle


推荐阅读