【问题标题】:How to display multidimensional array of json string in a table如何在表格中显示json字符串的多维数组
【发布时间】:2015-10-10 11:28:57
【问题描述】:

我通过 ajax 传递从数据库中获取的数据以显示在 html 页面中。我设法将它从 php 脚本传递到一个多维数组中。现在我得到了 json 字符串,但我不确定如何在 html 表中正确显示输出。

脚本

$("#submit").on("click",function()
    {

          $("#set_setting").submit(function(){            

            data = $(this).serialize()
            $.ajax({
              type: "POST",
              dataType: "html",
              url: "submit_setting.php", //Relative or absolute path to response.php file
              data: data,
              success: function(data) {
                  alert(data);
              //hide the form
              $("#set_setting").slideUp("slow");
              //show the result
             /* for (i = 0; i < data.length; i++) {
                  console.log(data);
                  $(".the-return").html(data);
              }*/

              console.log(data);
                $(".the-return").html(data);

              }

            });
            return false;

          });

        });

php 脚本

$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo json_encode($json);

数据输出

HondaHonda maker[{"type":["flying car","3 wheleer","weird car","miracle car","tata car","see car","star car","mn car","jkcar","car test","ting","Honda"],"maker":["test maker","diamond car","ruby car","dont know car","titi car","saw car","moon car","ty car","ty car","car maker test","ting maker","Honda maker"]}]

如何在 html 表格中显示这个 json 字符串?

【问题讨论】:

  • var 结果 = 数据; $.each($.parseJSON(result), function(k, v) { alert(k + ' is ' + v); });
  • 那么这个问题是关于 JS 而不是 PHP?!
  • 是的它是Js但我仍然使用php来传递数组
  • 除非我遗漏了什么,否则您显示的 Output of Data 不是有效的 JSON。 HondaHonda maker 不应该在那里。
  • @Vani - 好吧,你希望桌子是什么样子的?您基本上返回了两个数组。您是否希望有一个简单的 2 列表,每个数组在其中一列中?

标签: javascript php arrays json multidimensional-array


【解决方案1】:

这里有一些普通的 JS 可以解决问题。可能值得一提的是,您正在返回一个结果数组,其中只有一个元素。这就是我的代码中出现parsedResult[0] 的原因。如果您想返回多个 html 表的数据,您将有 parsedResult[1]、parsedResult[2] 等。此代码不考虑这种情况 - 我已经对其进行了硬编码以使用只是第一个。

结果:(请原谅 html 表格的文本格式,如果您愿意的话)

type    maker
flying car  test maker
3 wheleer   diamond car
weird car   ruby car
miracle car dont know car
tata car    titi car
see car saw car
star car    moon car
mn car  ty car
jkcar   ty car
car test    car maker test
ting    ting maker
Honda   Honda maker

代码:

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function newEl(tag){return document.createElement(tag);}

window.addEventListener('load', onDocLoaded, false);

var dummyResultString = '[{"type":["flying car","3 wheleer","weird car","miracle car","tata car","see car","star car","mn car","jkcar","car test","ting","Honda"],"maker":["test maker","diamond car","ruby car","dont know car","titi car","saw car","moon car","ty car","ty car","car maker test","ting maker","Honda maker"]}]';

function onDocLoaded()
{
    var ajaxResult = dummyResultString;
    var tblOfResults = parseAndCreateTable( ajaxResult );
    document.body.appendChild(tblOfResults);
}

function parseAndCreateTable(inputString)
{
    var rawResult = inputString;
    var parsedResult = JSON.parse(rawResult);
    var tableHeadings = [];

    // extract the name of the properties that the object has.
    for (var property in parsedResult[0]) 
    {
        if (parsedResult[0].hasOwnProperty(property))
            tableHeadings.push(property);
    }

    // make the table
    var tbl = newEl('table');
    var tbody = newEl('tbody');
    tbl.appendChild(tbody);

    // make the first row, with headings in it
    var tr = newEl('tr');
    var i, n = tableHeadings.length;
    for (i=0; i<n; i++)
    {
        var th = newEl('th');
        th.innerText = tableHeadings[i];
        tr.appendChild(th);
    }
    tbody.appendChild(tr);

    // now for the 'fun' part - the body itself.
    var curRowIndex, curColIndex, nRows = parsedResult[0][tableHeadings[0]].length, nCols = tableHeadings.length;
    for (curRowIndex=0; curRowIndex<nRows; curRowIndex++)
    {
        var tr = newEl('tr');
        for (curColIndex=0; curColIndex<nCols; curColIndex++)
        {
            var td = newEl('td');
            td.innerText = parsedResult[0][ tableHeadings[curColIndex] ][curRowIndex];
            tr.appendChild(td);
        }
        tbody.appendChild(tr);
    }

    return tbl; 
}
</script>
<style>
</style>
</head>
<body>
</body>
</html>

【讨论】:

  • 我是否需要包含任何库才能使此代码正常工作?我已将其复制粘贴到我的成功函数中,即使具有硬编码值,它也不会显示任何内容。
  • @Vani - 不。此代码没有依赖项。我已经更新了我的答案以包含一个功能齐全的示例。你的调试器告诉你是什么问题?
  • 实际上没有显示错误..但是我在ajax的成功函数中包含了这段代码但是你在head标签之前使用了......这可能是原因吗?我试图将它包含在 head 部分并在成功函数中调用该函数,但我仍然看不到表格
  • 有趣.. 好吧,您应该将 ajax 调用的结果传递给 parseAndCreateTable 函数,然后将结果附加到所需的容器中。实际上,我的代码在 inside 头部。您可以考虑的其他方法是使用 jQuery 方法设置 en 元素的 innerHTML - 只需从函数调用中获取表,然后获取它的 html,然后使用 jQuery 方法附加它。即`var resultTable = parseAndCreateTable(data); var tblHTML = resultTable.outerHTML; ** 使用 jQuery 方法设置元素的内容 **(我没有 jQuery,所以我不知道还有什么建议)
  • 我将您的函数包含在 head 中并将数据传递给 parseAndCreateTable 函数,然后像您提到的那样附加到容器中,它返回了表!谢谢!
【解决方案2】:

可能是这样的:

var typeMsg = ''
var makers = ''
if(data && data[0].type) {                //considering data is your response object
    for(var c in data[0].type) {
        typeMsg += c + ', ';
    }
}
if(data && data[0].maker) {   
    for(var c in data[0].maker) {
        makers += c + ', ';
    }
}

$('#elementForType').text(typeMsg && typeMsg.trim().replace(/,$/, "") + "." || 'No Type data available');
$('#elementForMakers').text(makers && makers.trim().replace(/,$/, "") + "."  || 'No makers data available');

【讨论】:

  • 它说,没有可用的类型数据没有可用的制造商数据
  • 试试 data[0].type 和 data[0].maker
  • 只需执行 JSON.stringify(data) 并将文本粘贴到此处。我需要看回复
  • [{"type":["4 Wheeler","flying ycar"],"maker":["Honda","AUdi"],"rate":[["1", "89"],["1","70"],["1","57"],["2","78"],["2","56"],["2", "34"]]}]
  • 我试过了,它输出了 0, 1, 2, 3, 4, 5, 6, 7. 两次。但它是什么?如何访问每个数组中的每个元素?
猜你喜欢
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 2013-05-11
  • 2020-10-31
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
相关资源
最近更新 更多