【问题标题】:Returned python values break html table after inserting in javascript array插入 javascript 数组后返回的 python 值破坏了 html 表
【发布时间】:2019-07-17 02:55:07
【问题描述】:

我正在尝试通过将 python 函数与 XMLHttpRequest() 接口来将从后端 python 函数返回的值显示到 html 表中。 1) 该表适用于没有 python 函数返回值的 javascript 数组。 2) 当 javascript 变量传递给 html 正文中的元素 id 时,python 函数调用起作用。 3)当python返回值被传递给javascript数组以显示在表中时,它会破坏表。谢谢。

模块

    class GetName:
        ...
        def get_name():
            return "Johnny Test"

烧瓶服务器

    ...
    @app.route('/record_status', methods=['POST'])
    def get_value():
        json = request.get_json()
        status = json['status']
        if status == "true":
            res = GetName.get_name()
            return jsonify(result=res)
    var myJSON;
    // When the user clicks the button, open the modal 
    btn.onclick = function() {
      modal.style.display = "block";

    // XMLHttpRequest
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
            //var myObj = JSON.parse(this.responseText);
            var myObj = JSON.parse(xhr.responseText);

            myJSON = JSON.stringify(myObj);
            document.getElementById("demo").innerHTML = myJSON;
          // alert(xhr.responseText);
          }
      };
      xhr.open("POST", "/record_status");
      xhr.setRequestHeader("Content-Type",     "application/json;charset=UTF-8");
      xhr.send(JSON.stringify({ status: "true" }));

      //function GenerateTable() {
                //Build an array containing Customer records.
      var customers = new Array();
      customers.push(["Customer Id", "Name", "Country"]);
      customers.push([1, 'John smith', "United States"]);
      customers.push([2, "Anita Ross", "Canada"]);
      customers.push([3, myJSON, "Mexico"]);

条件 1) 和 2) 处于正常工作状态。一旦将 var myJSON 插入数组中,表格就会中断

【问题讨论】:

    标签: javascript python flask


    【解决方案1】:

    有一种更简单的方法可以做到这一点,您可以使用 jquery 中的 ajax。如果您需要帮助解决问题,请回复或尝试观看此视频:我是如何学习的 Click here for vid

    【讨论】:

      【解决方案2】:

      onreadystatechange 在customers 创建后执行。因此,您的最后一个客户数据包含undefined。

      看来您需要将 customers 数组创建移至 onreadystatechange 函数。

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                  //var myObj = JSON.parse(this.responseText);
                  var myObj = JSON.parse(xhr.responseText);
      
                  var myJSON = JSON.stringify(myObj);
                  document.getElementById("demo").innerHTML = myJSON;
                // alert(xhr.responseText);
      
                  var customers = [];
                  customers.push(["Customer Id", "Name", "Country"]);
                  customers.push([1, 'John smith', "United States"]);
                  customers.push([2, "Anita Ross", "Canada"]);
                  customers.push([3, myJSON, "Mexico"]);
                }
            };
      

      【讨论】:

      • @riy 如果您希望人们帮助您,最好带上您拥有的所有信息。例如,与其说“不起作用”,不如说您现在看到的问题或错误是什么。
      • 请注意,我在发布问题之前已经尝试过您的解决方案,但无法生成表格。如帖子中所述,将返回的 var myJSON 推送到表时表中断,谢谢。
      • @riy 这意味着您只显示部分代码。真正的问题是表的生成。我假设代码在从服务器接收数据之前生成表。因此,显示更多代码会有所帮助。否则,这个问题应该被关闭。
      【解决方案3】:

      按照 Avi Baruch 的链接和一些修改以适应项目,使用 ajax 创建 html 以与 python 函数交互,响应在 python 函数中被 json 化并分配给一个名为 data 的字典键,同时呈现一个响应模板具有变量名 myList。响应模板允许循环返回的数据以传递给<div id="dvTable"></div> 中的模态内容。希望有人觉得这很有用,谢谢。

      #get_data.py : backend module return values 
      
      class GetData:
          def __init__(self):
              pass
      
          def records(self):
              return [(1, 'John Smith', 'Canada'),
                      (2, 'Jane Doe', 'United States'),
                      (3, 'John Doe', 'Mexico')]
      
      #app.py
      
      from flask import Flask, render_template, jsonify
      from get_data import GetData
      app = Flask(__name__)
      
      @app.route('/')
      def index():
          return render_template('index.html')
      
      @app.route('/_get_data/', methods=['POST'])
      def _get_data():
          data = GetData()
          myList = data.records()
          return jsonify({'data': render_template('response.html', myList=myList)})
      
      if __name__ == "__main__":
          app.run(debug=True)
      
      
      <!--templates/index.html-->
      <!doctype html>
      <html lang="en">
          <head>
              <meta charset="utf-8">
              <style>
      body {font-family: Arial, Helvetica, sans-serif;}
      
      /* The Modal (background) */
      .modal {
        display: none; /* Hidden by default */
        position: fixed; /* Stay in place */
        z-index: 1; /* Sit on top */
        padding-top: 100px; /* Location of the box */
        left: 0;
        top: 0;
        width: 100%; /* Full width */
        height: 100%; /* Full height */
        overflow: auto; /* Enable scroll if needed */
        background-color: rgb(0,0,0); /* Fallback color */
        background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
      }
      
      /* Modal Content */
      .modal-content {
        background-color: #fefefe;
        margin: auto;
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
      }
      
      /* The Close Button */
      .close {
        color: #aaaaaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
      }
      
      .close:hover,
      .close:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
      }
      </style>
          </head>
      
          <body>
       <!-- Trigger/Open The Modal -->
      <button id="myBtn">Open Modal</button>
      
      <!-- The Modal -->
      <div id="myModal" class="modal">
      
        <!-- Modal content -->
        <div class="modal-content">
          <span class="close">&times;</span>
          <div id="dvTable"></div>
        </div>
      </div>
      <style>
      table {
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 100%;
      }
      
      td, th {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
      }
      
      tr:nth-child(even) {
        background-color: #dddddd;
      }
      </style>
      
      <script src="https://code.jquery.com/jquery-3.4.1.js"
        integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
        crossorigin="anonymous">
      </script>
      
      <script>
      // Get the modal
      var modal = document.getElementById("myModal");
      
      // Get the button that opens the modal
      var btn = document.getElementById("myBtn");
      
      // Get the <span> element that closes the modal
      var span = document.getElementsByClassName("close")[0];
      
      
      // When the user clicks the button, open the modal 
      btn.onclick = function() {
        modal.style.display = "block";
        //var Table = document.getElementById("dvTable").innerHTML = "";
        //prevent duplicates
        $("#dvTable tr").remove(); 
             //get the data and append to the table
             $.ajax({
                  url: "/_get_data/",
                  type: "POST",
                  success: function(resp){
                      $('div#dvTable').append(resp.data);
                  }
              });
      }
      
      // When the user clicks on <span> (x), close the modal
      span.onclick = function() {
        modal.style.display = "none";
      
      }
      
      // When the user clicks anywhere outside of the modal, close it
      window.onclick = function(event) {
        if (event.target == modal) {
          modal.style.display = "none";
        }
      }
      </script>
      
      </body>
      </html>
      
      <!--templates/response.html: layout template to iterate through the data-->
      
          <table>
                  <tr>
                      <th>Customer ID</th>
                      <th>Name</th>
                      <th>Country</th>
                  </tr>
                  {% for elem in myList %}
                  <tr>
                      <td>{{elem[0]}}</td>
                      <td>{{elem[1]}}</td>
                      <td>{{elem[2]}}</td>
                  </tr>
                  {% endfor %}
          </table>
      
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-09
        • 1970-01-01
        • 1970-01-01
        • 2020-02-17
        相关资源
        最近更新 更多