【问题标题】:Load the data into html table from json formatted variable从 json 格式的变量将数据加载到 html 表中
【发布时间】:2021-10-20 04:53:23
【问题描述】:

我需要将从 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>

【问题讨论】:

  • 您在 JavaScript 文件中使用的键 User_Name 、 score 和 team 不会作为 Python 脚本数据的一部分返回。您需要确保引用的密钥可用
  • 更新代码。

标签: javascript python html


【解决方案1】:

一个明显的错误是:

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

应该是

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

【讨论】:

  • 我添加 # 仍然无法填充 html 表。我尝试了 alert() 方法来查看从 python 函数返回的内容,这是正确的 json 格式字符串 [{"url_id": 1, "url": "www.google.com", "regime": "FATCA", "jurisdiction": "SG"}] 但是,当我尝试遍历它时,我收到未定义的消息。
  • 所以,我可以通过使用 JSON JSON.parse(data) 解析字符串来解决这个问题
猜你喜欢
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 2018-07-09
  • 2011-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多