【问题标题】:display json result in table format from sqlite database file从 sqlite 数据库文件以表格格式显示 json 结果
【发布时间】:2017-12-04 07:21:58
【问题描述】:

我想显示来自 mysqlite 数据库文件的数据。这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <title>My App</title>
    <script src="sql.js"></script>

</head>
<body>
<h1>My App</h1>
<div id="res" style="width: 100%">
</div>
<script>
    function loadBinaryFile(path,success) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", path, true); 
        xhr.responseType = "arraybuffer";
        xhr.onload = function() {
            var data = new Uint8Array(xhr.response);
            var arr = new Array();
            for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
            success(arr.join(""));
        };
        xhr.send();
    };


    loadBinaryFile('MyData.db', function(data){
        var db = new SQL.Database(data);

        var res = db.exec("SELECT * FROM MyRecord");
      // document.getElementById("demo").textContent = JSON.stringify(res);
        var data=JSON.stringify(res);
      document.getElementById("res").textContent=data;


});

</script>
</body>
</html>

我得到这种格式的输出:

[{"columns":["id","name","gender","fname"],"values":[[1,"divya","female","rao"],[3,"nithin","male","kumar"]]}]

现在,如何以表格格式显示这个 json 数据。谁能帮帮我?

【问题讨论】:

    标签: javascript json html sqlite


    【解决方案1】:

    var data = [{"columns":["id","name","gender","fname"],"values":[[1,"divya","female","rao"],[3,"nithin","male","kumar"]]}];
    
    data = data[0];
    
    
    var html = '<table><tr>';
    
    data.columns.forEach(d => {
    	html += '<th>' + d + '</th>'
    });
    
    html += '<tr>';
    
    data.values.forEach( row => {
    	html += '<tr>';
    	row.forEach( item => {
      	html += '<td>'+ item +'</td>'
      });
      html += '</tr>';
    });
    
    document.body.innerHTML = html;

    【讨论】:

    • 当我添加此代码时,我得到了类似“无法读取未定义的属性'forEach'”的错误,而且我使用了 var db = new SQL.Database(data);在我的代码中。
    • 我已经使用数据作为变量名。您可以将其重命名为 jsonData。上面贴出的代码将上面指定的json格式转换成html表格语法。
    • 对不起。我也使用了相同的变量名,即var data=JSON.stringify(res);我得到了那个错误。如果我按照您的指定对 json 数据进行硬编码,则会得到输出。如果我使用 JSON.stringify(res) 而不是那样,得到错误
    • 不要字符串化响应。只需使用 res 而不是 sn-p 中的数据。它应该可以工作,因为 res 的格式是[{"columns":["id","name","gender","fname"],"values":[[1,"divya","female","rao"],[3,"nithin","male","kumar"]]}]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多