从本地存储中获取数据并附加到html作为li?

时间:2017-03-09 17:39:15

标签: jquery html json ajax local-storage

我不确定下一步做什么是正确的步骤但是现在我让我的外部json文件执行get请求然后将它放入div中。如何使每个对象成为列表项?而不是在网页上看起来像这样? https://ibb.co/cxU4Aa

谢谢!

$(function () {
  getStarterMenuData();
});

function getStarterMenuData() { //AJAX http get request
  $.get(
    'data/startersMenu.json',
    function (data) {
      window.localStorage.setItem('starterMenu', JSON.stringify(data)); //Calls local storage API, stores key/value into local storage
    },
    'json'
    );
}

  var data;
  data = JSON.parse(window.localStorage.getItem('startersMenu')); //Gets the data from local storage
  document.getElementById("starters").innerHTML = localStorage.getItem("starterMenu");

外部json文件看起来像这样

[

{
 "name": "Jumbo Lump Crab Cake",
 "description": "Creole lobster sauce."
},

{
  "name": "Bacon Wrapped Sea Scallops",
  "description": "Chardonnay lemon sauce, Mango salsa."
},
{
  "name": "Chilled Maine Lobster Cocktail",
  "description": "Atomic cocktail sauce and lemon butter."
},
{
  "name": "Coconut Shrimp",
  "description": "three jumbo tiger shrimp, vanilla orange beurre blanc."
},
{
  "name": "Crispy Point Judith Calamari",
  "description": "Italian peppers and Bleu cheese Stuffed olives, Atomic cocktail sauce."
},
{
  "name": "Oysters on the Half Shell",
  "description": "shucked to order, mignonette and Atomic cocktail sauces."
}

]

3 个答案:

答案 0 :(得分:0)

迭代您的数据并创建li,如下所示。

var data = JSON.parse(window.localStorage.getItem('startersMenu'));

data.forEach(function(item) {
    var $ul = $("#starters");        
    $ul.append('<li>'+ item.name + '</li>');
})

答案 1 :(得分:0)

对您的数据执行map(或循环)。所以做这样的事情:

document.getElementById("starters").html(JSON.parse(localStorage.getItem("starterMenu")).map(function(data) {
    var $list = $('<li>');
    $list.append($('<h1>', { text: data.name }));
    $list.append($('<div>', { text: data.description }));
    return $list;
}));

注意:值得将文本添加为​​实际文本而不是HTML以防止XSS。

答案 2 :(得分:0)

您只需遍历返回的数据,创建您的html,然后将其呈现到页面

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myData"></div>
&#13;
{{1}}
&#13;
&#13;
&#13;