【问题标题】:retrieving JSON object using a html link and displaying the json data on a html page使用 html 链接检索 JSON 对象并在 html 页面上显示 json 数据
【发布时间】:2018-09-08 01:27:00
【问题描述】:

我想在用户单击 html 链接时检索 JSON 对象。我想通过它的 ID 检索它并在 html 页面上显示对象中的所有内容。我也在使用会话存储.....我希望用户在点击 html 链接后被带到 info.html 页面。

到目前为止我的 html 代码:

<div class="col">
    <!-- team-img -->
    <div class="team-block">
        <div class="team-content">
            <h4 class="text-white mb0">Chocolate Cake </h4>
            <p class="team-meta">Large</p>
        </div>
        <div class="overlay">
            <div class="text">
                <h4 class="mb0 text-white"> Chocolate Cake </h4>
                <p class="mb30 team-meta"> Large </p>
                <p>Large Chocolate cake. 15 servings.</p>
                <p><a href="info.html" id="1">Further info</a></p>
            </div>
        </div>
    </div>
</div>

在 JSON 文件中蛋糕的 ID 为“1”。我希望在用户单击链接时显示蛋糕的所有详细信息。我希望将用户带到 info.html。存储在 JSON 中的蛋糕数据应显示在那里。问题出在这一行:

<p><a href="info.html" id="1">Further info</a></p>

我的 JSON 文件名为 cakes.json

下面是我的 .js 文件

var ajax=function(url,success)
{
    var ajaxRequest = new XMLHttpRequest(); 
    var handleResponse=function()
    {
        if(ajaxRequest.readyState===4)
        {
            if(ajaxRequest.status===200)
            {
                var data=JSON.parse(ajaxRequest.responseText);
                success(data); //this will call populateList
            }
        }
    }
    ajaxRequest.addEventListener("readystatechange",handleResponse,false); 
    ajaxRequest.open('GET', url, true);
    ajaxRequest.send(null);
}

var navList;
var contentDiv;

function createHandler(car)
{
    return function(){
        sessionStorage.setItem("cake",JSON.stringify(cake));
    }
}

function populateList(cakes)
{
    navList=document.getElementById("nav");
    contentDiv=document.getElementById("content");

    cakes.forEach(function(cake){
        var newLi=document.createElement("ul");
        var newLink=document.createElement("a");
        newLink.innerHTML=cake.name;
        newLink.setAttribute("href","info.html");
        newLink.addEventListener("click", createHandler(cake), false)
        newLi.appendChild(newLink);
        navList.appendChild(newLi);
    })
}

function init(){
    ajax("data/cakes.json",populateList);
}

init();

JSON 文件:

[
        {
        "id":1,
        "cake":"chocolate cake",
        "servings":"15",
        "size":"10",
        "code":"ed39"   
    },

]

任何帮助将不胜感激。

【问题讨论】:

  • 你应该修改你在a标签中发送的href以包含info.html?id=1(查询参数)并且在你的脚本中你应该检索这个id来获得所需的json值。
  • 你应该有一个 function 来解析 json 并检索所需 id 的信息,如果你可以把 json 放在这里,我可以帮助你
  • 执行sessionStorage.setItem("cake",JSON.stringify(cake))时没有cake
  • 您能更改我的代码并告诉我它是如何完成的吗?正如我之前尝试过但失败了。
  • 我已经添加了我的 JSON 文件 Sabbin

标签: javascript html json


【解决方案1】:

我已经做了一个示例,说明如何使用包含多个 objectsarray 结构来完成此操作。我还修改了您的html 添加了data-id 参数而不是id 通常您不会将对象的id 保存在html 元素的id 中(不是最佳实践),您可以使用data- 参数,jQuery 中还有一个函数可以读取这些参数 $(selector).data('identifier')

var json = [{
  "id": 1,
  "cake": "chocolate cake",
  "servings": "15",
  "size": "10",
  "code": "ed39"
}, {
  "id": 2,
  "cake": "vanilla cake",
  "servings": "15",
  "size": "10",
  "code": "ed39"
}];

$(document).on('click', '.cakeDetailsButton', function() {
  var id = $(this).data('id'),
    details = getDetailsById(id), //Here all the details for the cake
    resultDiv = $('.result');
  resultDiv.text('');
  $.each(details, function(key, value) {
    resultDiv.append(key + ' -- ' + value + '<br/>') // Here you can do whatever with the details
  })
});

function getDetailsById(id) {
  for (var i = 0; i < json.length; i++) {
    if (json[i].id == id) {
      return json[i];
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><a class="cakeDetailsButton" href="#" data-id="1">Further info 1</a></p>
<p><a class="cakeDetailsButton" href="#" data-id="2">Further info 2</a></p>
<div class="result">

</div>

编辑 - 更新

为了在localStorage 中添加您的json 以便从任何地方访问它,请更新以下内容

.js 文件

function populateList(cakes)
{
    localStorage.setItem('cakesJson', cakes); //This adds an object to the localStorage with the key cakesJson and value the cakes object
    navList=document.getElementById("nav");
    contentDiv=document.getElementById("content");

    cakes.forEach(function(cake){
        var newLi=document.createElement("ul");
        var newLink=document.createElement("a");
        newLink.innerHTML=cake.name;
        newLink.setAttribute("href","info.html");
        newLink.addEventListener("click", createHandler(cake), false)
        newLi.appendChild(newLink);
        navList.appendChild(newLi);
    })
}

然后在我上面提供的代码中,您应该更改以下内容

function getDetailsById(id) {
  var json = localStorage.getItem("cakesJson"); // Here you retrieve the values stored in the localStorage
  for (var i = 0; i < json.length; i++) {
    if (json[i].id == id) {
      return json[i];
    }
  }
}

事件监听器和 sn-p 中的一样

$(document).on('click', '.cakeDetailsButton', function() {
  var id = $(this).data('id'),
    details = getDetailsById(id), //Here all the details for the cake
    resultDiv = $('.result');
  resultDiv.text('');
  $.each(details, function(key, value) {
    resultDiv.append(key + ' -- ' + value + '<br/>') // Here you can do whatever with the details
  })
});

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2013-06-04
    • 1970-01-01
    • 2017-06-04
    • 2017-12-25
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多