首页 > 解决方案 > 从 json 格式的变量将数据加载到 html 表中

问题描述

我需要将从 python 脚本返回的 json 转储数据加载到我的 html 表中,不确定我做错了什么,因为我对 html 相对较新并且为 POC 执行此操作。我无法将数据加载到 html 表中。寻求你的帮助。

Python Code
def read_data_from_sql(sqlserverinst,uname,psswd,dbname,url,regime,jurisdiction):
    output=[]
    conn = pymssql.connect(sqlserverinst, uname, psswd, dbname)
    cursor = conn.cursor(as_dict=True)
    cursor.execute('SELECT * FROM [reg_content_extracted_url_browsed]')
    for row in cursor:
    output.append({'url_id': row['url_id'],'url': row['url'],'regime': row['regime'],'jurisdiction': row['jurisdiction']})
    # flat_list = [item for sublist in output for item in sublist]
    conn.close()
    print(json.dumps(output))
    return json.dumps(output)

输出格式:[{"url_id": 1, "url": "www.google.com", "regime": "FATCA", "jurisdiction": "SG"}]

HTML Table layout
<div class="content-large">Successful Browsed URL(s)
    
    <!-- <style>
        table, th, td {
        border:1px solid black;
        }
    </style> -->
    <table id="btable" style="width:100%">
        <tr style="color: white;">
          <th>url id ID</th>
          <th>url</th>
          <th>Regime</th>
          <th>Jurisdiction</th>
        </tr>
        <tr>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          
        </tr>            
    </table>
</div>

Script to populate json data
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> 
</script>
<script type=text/javascript>
$(function() {
  $('a#test').on('click', function(e) {
    e.preventDefault()
    $.get('/datahomepage',
        function(data) {
            // alert(data);
            alert(data.length)
            // console.console.log("hheh"); 
            var tr;
            for (var i=0;i<data.length;i++){

                alert(data[i].url_id)
                tr = $('<tr/>');
                tr.append("<td>" + data[i].url_id+ "</td>");
                tr.append("<td>" + data[i].url+ "</td>");
                tr.append("<td>" + data[i].regime+ "</td>");
            $('btable').append(tr);
            }
            
    });
    // return false;
  });
});
</script>

标签: javascriptpythonhtml

解决方案


一个明显的错误是:

$('btable').append(tr);

应该是

$('#btable').append(tr);

推荐阅读