简体   繁体   English

访问 javascript function 中的字典/json 以填充表时出现问题

[英]Problems accessing a dictionary/json in a javascript function to populate a table

Overview: I am creating a web page using Python and generating both html as well as javascript in my code.概述:我正在使用 Python 创建一个 web 页面,并在我的代码中生成 html 和 ZDE9B9ED78D7E2E19ZEFFEE 代码。 Additionally, I am parsing through csv files and converting their table data to html.此外,我正在解析 csv 文件并将其表数据转换为 html。 I want to be able to click on a line of text and the associated table data for that text would then be loaded into an iframe on the currently active web page.我希望能够单击一行文本,然后将该文本的关联表格数据加载到当前活动的 web 页面上的 iframe 中。 The problem I am having, is that my javascript function is not recognizing the key I send it to retrieve the corresponding table data.我遇到的问题是我的 javascript function 无法识别我发送它以检索相应表数据的密钥。 If I manually enter the key to return the table data, the correct data is returned - though the table doesn't load.如果我手动输入返回表数据的密钥,则会返回正确的数据——尽管表没有加载。 However, if I generate the key programmatically, it returns as 'undefined' even though the strings appear to be identical.但是,如果我以编程方式生成密钥,即使字符串看起来相同,它也会返回为“未定义”。

Goal: I need to figure out if there is something wrong with either the syntax, or the format of the key I am using to try and retrieve the table data.目标:我需要弄清楚我用来尝试检索表数据的语法或键的格式是否有问题。 Secondly, I need to figure out why the table data is not being correctly loaded into my iframe.其次,我需要弄清楚为什么表数据没有正确加载到我的 iframe 中。

Example:例子:

import pandas

opening_html =  """<!DOCTYPE html><h1> Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe name="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """<a href='' onclick="send_table_data(this);"> test-1</a><br>"""
java = """<script type='text/javascript'>
            var table_filename = """ + java_variables + ";"
            
java += """function send_table_data(obj) {
            var t = obj.text + ' 00';
            alert(t)
            //This line below will not work
            var table_data = table_filename[t];
            //But this line will return the correct value
            var table_data = table_filename['test-1 00'];
            alert(table_data);
            //This line should load the data, but does nothing
            document.getElementsByName('table_frame').src = table_data;
        }
        </script>"""

html_text = """<head>
                <link rel="stylesheet" href="style.css">
                </head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'

with open('test_table_load.html', 'w') as w:
    w.write(html_text)

EDIT: I did just figure out that for some reason there was a default space at the beginning of the var t - so using trim() seemed to fix that.编辑:我刚刚发现由于某种原因在 var t 的开头有一个默认空间 - 所以使用 trim() 似乎可以解决这个问题。 Now, the only issue left is why the data doesn't load into the table.现在,剩下的唯一问题是为什么数据没有加载到表中。

It looks like you figured out your typo with the space that was messing with your key, so this is for your second question.看起来你用弄乱你的钥匙的空间找出了你的错字,所以这是你的第二个问题。

Your code你的代码

So to get your table to populate in the iframe you need to fix three things:因此,要让您的表填充到 iframe 中,您需要修复三件事:

  1. To edit the HTML contents of your iframe you should be setting the .srcdoc element, not .src要编辑 iframe 的 HTML 内容,您应该设置.srcdoc元素,而不是.src

  2. The document.getElementsByName() function will return an array of HTML elements so in order to get the element you want you should do one of the following: document.getElementsByName() function 将返回 HTML 元素的数组,因此为了获得您想要的元素,您应该执行以下操作之一:

    • (recommended) switch to using document.getElementById and use id='table_frame' in your iframe tags (推荐)切换到使用document.getElementById并在 iframe 标签中使用id='table_frame'
    • select the first element of the array by using document.getElementsByName('table_frame')[0] select 数组的第一个元素使用document.getElementsByName('table_frame')[0]
  3. The anchor tag that you're using as the trigger for your function is redirecting you back to the original HTML page, stopping you from seeing any of the changes your javascript function is making. The anchor tag that you're using as the trigger for your function is redirecting you back to the original HTML page, stopping you from seeing any of the changes your javascript function is making. A simple solution to this is to switch to using a <button> element in place of <a> .一个简单的解决方案是切换到使用<button>元素代替<a>

Here is what your code looks like with the fixes:这是您的代码在修复后的样子:

import pandas
import json

opening_html =  """<!DOCTYPE html><h1>Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe id="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """<button href='' onclick="send_table_data(this);"> test-1</button><br>"""
java = """<script type='text/javascript'>
            var table_filename = """ + java_variables + ";"
            
#for the button, innerText needs to be used to get the button text
java += """function send_table_data(obj) {
            var t = obj.innerText + ' 00';
            alert(t)
            //This line below will not work
            var table_data = table_filename[t];
            //But this line will return the correct value
            var table_data = table_filename['test-1 00'];
            alert(table_data);
            //This line should load the data, but does nothing
            document.getElementById('table_frame').srcdoc = table_data;
        }
        </script>"""

html_text = """<head>
                <link rel="stylesheet" href="style.css">
                </head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'

with open('test_table_load.html', 'w') as w:
    w.write(html_text)

Other Recommendations其他建议

I strongly suggest looking into some python frameworks that can assist you in generating your website, either using HTML templates like Flask , or a library that can assist in generating HTML using Python. I strongly suggest looking into some python frameworks that can assist you in generating your website, either using HTML templates like Flask , or a library that can assist in generating HTML using Python. (I would recommend Dash for your current use case) (我会为您当前的用例推荐Dash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM