如何将JSON数据显示在HTML div中? [英] How do I get JSON data to show up in HTML div?

查看:104
本文介绍了如何将JSON数据显示在HTML div中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让这个json数据显示在HTML div中

Trying to get this json data to show up in HTML div

[{
  "botten": ["Krispig", "tunn"]
},
]  

div在HTML文档中具有类名 box1_data 。这是我的脚本:

The div in the HTML document has the class name box1_data. This is my script:

var bottenInfo = document.getElementsByClassName("box1_data");

$.getJSON('choosepizza.json', function(choosePizzaData) {
  choosePizza(choosePizzaData);

  function choosePizza(choosePizzaData) {
    var request = new XMLHttpRequest();
    request.open('GET', 'choosepizza.json');
    request.onload = function() {
      var data = JSON.parse(request.responseText);
      renderHTML(data);
    };
    request.send();

    function renderHTML(bottenData) {
      var text = "";
      for (var i = 0; i < bottenData.length; i++) {
        text += '<p>' + bottenData[i].botten + '<p>';
      }
      bottenInfo.innerHTML = text;
    }
  });

我做错了什么?

krispig tunn 应该出现在 .box1_data div。

krispig and tunn is supposed to show up in the .box1_data div.

推荐答案

您的代码似乎相当困惑普通JS和jQuery之间的区别以及AJAX的工作原理。您当前正在使用不同的逻辑两次发出相同的请求,解析已经解析的对象,未正确访问结果对象,并尝试将节点集合作为单个元素进行访问。

Your code seems rather confused regards to the difference between plain JS and jQuery and also how AJAX works. You're currently making the same request twice using different logic, parsing an object that's already been parsed, not correctly accessing the resulting object, and are attempting to access a node collection as a single element.

要解决此问题,您只需循环遍历结果,该结果将自动反序列化为对象,并生成要放置在所需元素中的HTML:

To fix this you simply need to loop through the result, which will be deserialised to an object for you automatically, and generate the HTML to be placed in the required element:

$.getJSON('choosepizza.json', function(choosePizzaData) {
  var html = choosePizzaData[0].botten.map(function(botten) {
    return '<p>' + botten + '</p>';
  });
  $(".box1_data").html(html);
});

这是一个没有AJAX的工作示例,显然在SO上不起作用:

This is a working example without the AJAX which obviously won't work here on SO:

// the response from the request:
var choosePizzaData = [{
  "botten": ["Krispig", "tunn"]
}]

// within the AJAX callback
var html = choosePizzaData[0].botten.map(function(botten) {
  return '<p>' + botten + '</p>';
});
$(".box1_data").html(html);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1_data"></div>

这篇关于如何将JSON数据显示在HTML div中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆