在javascript数组中插入后,返回的python值会破坏html表

问题描述:

我正在尝试通过将python函数与XMLHttpRequest()接口来将后端python函数返回的值显示到html表中.1)该表可与javascript数组一起使用,而无需返回python函数的值.2)当javascript变量传递到html正文中的元素ID时,python函数调用起作用.3)当python返回的值传递到javascript数组以显示在表中时,它将破坏表.谢谢.

I am trying to display values returned from a backend python function into an html table by interfacing the python function with XMLHttpRequest(). 1) The table works with javascript array without the python function returned value. 2) The python function call works when the javascript variable is passed to an element id in the html body. 3) It breaks the table when the python returned value is passed to a javascript array to display in the table. Thank you.

模块

    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插入数组,表就会中断

condition 1) and 2) in working order. The table breaks once the var myJSON is inserted in the array

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

Following Avi Baruch's link and some modifications to suit the project, the html is created with ajax to interface with the python function, the response is jsonified within the python function and assigned to a dictionary key called data, while rendering a response template with a variable name myList. The response template allows to loop over the returned data to be passed unto the modal content in <div id="dvTable"></div>. Hope someone finds this useful, thanks all.

#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>