【问题标题】:How to put JSON data into a HTML div?如何将 JSON 数据放入 HTML div?
【发布时间】:2018-05-23 00:07:27
【问题描述】:

这是我的问题:我想将通过 Ajax 调用捕获的 JSON 数据放入 HTML div 中。

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}
<div id="output"></div>

以下是变量数据包含的内容:

如何在 HTML div 中显示变量的内容 - 特别是在表格中?

【问题讨论】:

  • 使用 JSON.stringify 函数
  • 您可能需要先对数据进行字符串化。 $('#outpu't).html(JSON.stringify(data)).
  • 字符串化看起来像这样:{"NOMA":["Chachi","Rafiki","Chakra"],"SEXE":["F","M","F" ],"DATENAISSANCE":["05-MAY-15","07-JAN-15","17-SEP-17"]} 并不是每个人都能真正阅读
  • 是的,但它是您可以拥有 JSON 的最易读的形式。
  • 使用 JSON.stringify(data,null,4) 以 4 个空格缩进漂亮地打印输出。

标签: javascript jquery html json ajax


【解决方案1】:
var data = {
    DATENAISSANCE: [...],
    ...
}

var root = document.getElementById("output");
var table = element("table");
root.appendChild(table);

var dataName;
for (dataName in data) {
    if (data.hasOwnProperty(dataName)) {
        var row = element("tr", element("th", dataName));
        data[dataName].forEach(function (dataValue) {
            row.appendChild(element("td", dataValue));
        });
        table.appendChild(row);
    }
}


// Create a convenient function `element` which creates an element and sets its content
function element(nodeName, content, attributes, eventListeners) {
    var node = document.createElement(nodeName);
    appendChildren(node, content);
    return node;
}

function appendChildren(node, content) {
    var append = function (t) {
        if (/string|number/.test(typeof t)) {
            node.innerHTML += t;
        } else if (t instanceof HTMLElement) {
            node.appendChild(t);
        }
    };
    if (content instanceof Array) {
        content.forEach(function (item) {
            append(item);
        });
    } else {
        append(content);
    }
}

【讨论】:

    【解决方案2】:

    你可以使用pre标签来显示JSON。

    var data = {"NOMA":["Chachi","Rafiki","Chakra"],"SEXE":["F","M","F"],"DATENAISSANCE":["05-MAY-15","07-JAN-15","17-SEP-17"]};
    $('pre').html(JSON.stringify(data, undefined, 2));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <pre></pre>

    【讨论】:

      【解决方案3】:

      由于您返回的数据已经是 JSON 格式,我建议您使用 $.getJSON 并在 getespece.php 中通过 $_GET 变量更改您的 $_POST。

      另外,您的 JSON 对象的格式似乎有点不正确。如果您想在 HTML 表格中显示您的“especes”,正确的 JSON 格式可能是这样的:

      {
          "Columns": [
              "DateDeNaissance",
              "Nom",
              "Sexe"
          ],
          "Especes": [{
              "DateDeNaissance": "05-MAY-15",
              "Nom": "Chachi",
              "Sexe": "F"
          }, {
              "DateDeNaissance": "07-JAN-15",
              "Nom": "Rafiki",
              "Sexe": "M"
          }, {
              "DateDeNaissance": "17-SEP-17",
              "Nom": "Chakra",
              "Sexe": "F"
          }]
      }
      

      一旦你从你的 PHP 得到这个输出,把你的 JS 改成这样:

      $.getJSON("getespece.php", {
          espece: espece,
          categorie: categorie
      })
      .done(function(json) {
          // Build the html Table
          var html = "<table>\n";
              html += "<thead>\n";
              html += "<tr>\n";
          // Columns
          $.each(json.Columns, function(k, value) {
              html += "<th>" + column + "</th>\n";
          });
          html += "</tr>\n";
          html += "<tbody>\n";
          // Rows
          $.each(json.Especes, function(column, values) {
              html += "<tr>\n";
              // Cells
              $.each(values, function(k, val) {
                  html += "<td>" + val + "</td>\n";
              });
              html += "</tr>\n";
          });
          html += "</tbody>\n";
          html += "</table>\n";
          $("#output").html(html);
      });
      

      【讨论】:

        【解决方案4】:

        由于您的 json 数据子项是数组,您可以使用 $.each 函数:

        例子:

        var noma = data.NOMA;
        var html_append = '';
        $.each(noma, function(key,value) {
           html_append += value +'<br>';
        });
        
        $('#output').html(html_append);
        

        同样的代码也可以用于 data.DATENAISSANCE 和 data.SEXE

        【讨论】:

          【解决方案5】:

          你的数据变量是一个 JS 对象,你需要在调用 $('#output').html(data) 之前将其转换为字符串或你想要显示的格式。 您可以执行以下操作:

          function showEspece(espece, categorie, object) 
            {
              $.ajax({           
                type : 'POST',                           
                url: 'getespece.php',                  
                data: {espece: espece, categorie: categorie },                       
                dataType: 'json',                     
                success: function(data)          
                {
                  console.log(data);
                  data = JSON.stringify(data)     
                  $('#output').html(data); //what i try to do but don't work
                },
                error: function(xhr, status, error) {
                  console.log(error);
                }
              });
            }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-01-19
            • 2018-05-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-10-12
            • 1970-01-01
            • 2011-11-14
            相关资源
            最近更新 更多