繁体   English   中英

将烧瓶列表传递到HTML

[英]passing Flask list to HTML

我正在尝试将Flask列表传递给HTML,但是由于某种原因,输出是空白的HTML页面。 以下是我将列表发送到Python的HTML和Javascript代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="/static/script.js"></script>
        <script type="text/javascript"></script>
        <title>Vodafone Comms Checker</title>
        </head>
        <body>
    <form name="ResultPage" action="passFails.html" onsubmit="return validateTestPage()" method="post">
         Number of Hosts/Ports:<br><input type="text" id="Number"><br/><br/>
        <a href="javascript:void(0)" id="filldetails" onclick="addFields()">Enter Comms Details</a>
        <div id="container"/>
    </form>
    </body>
</html>

这是JavaScript代码:

function validateLoginPage() {
    var x = document.forms["loginPage"]["sourcehost"].value;
    var y = document.forms["loginPage"]["username"].value;
    var z = document.forms["loginPage"]["psw"].value;
    if(x=="" ||y=="" || z==""){
         alert("Please fill empty fields");
         return false;
    }
    else{
        return true;

    }
}
function validateTestPage() {
    var a = document.forms["ResultPage"]["DestinationHost"].value;
    var b = document.forms["ResultPage"]["port"].value;
    if(a=="" ||b==""){
         alert("Please fill empty fields");
         return false;
    }
    else{
        return true;

    }
}

    function addFields(){
                // Number of inputs to create
                var number = document.getElementById("Number").value;

                // Container <div> where dynamic content will be placed
                var container = document.getElementById("container");

                // Clear previous contents of the container
                while (container.hasChildNodes()) {
                    container.removeChild(container.lastChild);
                }

                for (var i=1;i<=number;i++){
                    container.appendChild(document.createTextNode("Host: " + i));
                    var host = document.createElement("input");
                    host.type = "text";
                    host.id = "Host " + i;
                    container.appendChild(host);

                    container.appendChild(document.createTextNode("Port: " + i));
                    var port = document.createElement("input");
                    port.type = "text";
                    port.id = "Port " + i;
                    container.appendChild(port);

                    // Append a line break
                    container.appendChild(document.createElement("br"));
                    container.appendChild(document.createElement("br"));
    }
        var button = document.createElement("input");
        button.setAttribute("type", "button");
        button.setAttribute('value', 'Check');
        button.setAttribute('onclick', 'checkVal()');
        container.appendChild(button);

        return true;
    }



    function checkVal() {
        var myHost=[];
        var myPort=[];
    // Number of inputs to create
        var number = document.getElementById("Number").value;

        for (var i = 1; i <= number; i++) {

            //pass myHost and myPort to first.py for further processing.

             myHost.push(document.getElementById('Host ' + i).value);
             myPort.push(document.getElementById('Port ' + i).value);
        }

        for (var i=0; i<number; i++){

            alert("Value of Host: " + (i+1) + " is: " + myHost[i]);
            alert("Value of Port: " + (i+1) + " is: " + myPort[i]);
        }
         $.get(
            url="/passFails",
            data={'host' : myHost},
            success = function () {
                console.log('Data passed successfully!');
            }
        );

        return true;
    }

这是我的Python代码,在这里我可以成功接收列表,甚至遍历值,但是脚本无法将列表发送到我的HTML页面。

from flask import Flask, render_template, request
import json
import jsonify

app = Flask(__name__)


@app.route('/Results')
def results():

    return render_template('Results.html')


@app.route('/passFails')
def pass_fails():

    host_list = request.args.getlist('host[]')

    print("Value of DATA variable in passFails Decorator is: %s" % host_list)

    for val in host_list:

        print("The value in VAL Variable is: %s" % val)

    return render_template('passFails.html', hosts=host_list)


if __name__ == '__main__':
    app.run(debug=True)

下面是应该打印从python发送的列表的HTML,但是我得到的只是一个空白页。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="/static/script.js"></script>
    <script type="text/javascript"></script>
    <title>Vodafone Comms Checker</title>
</head>
<body>
<ul>
    {% for host in hosts %}

    <li>In the Host text box, you entered: {{ host }}</li>

    {% endfor %}
</ul>

</body>
</html>

下面是我运行程序时的输出:

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /Results HTTP/1.1" 200 -
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /static/script.js HTTP/1.1" 200 -
127.0.0.1 - - [24/Feb/2019 13:44:44] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [24/Feb/2019 13:44:56] "GET /passFails?host%5B%5D=a&host%5B%5D=b&host%5B%5D=c HTTP/1.1" 200 -
Value of DATA variable in passFails Decorator is: ['a', 'b', 'c']
The value in VAL Variable is: a
The value in VAL Variable is: b
The value in VAL Variable is: c
Value of DATA variable in passFails Decorator is: []
127.0.0.1 - - [24/Feb/2019 13:45:03] "GET /passFails HTTP/1.1" 200 -

谁能告诉我代码有什么问题,为什么我不能将我的Python列表发送到HTML?

在您的checkVal()函数中,您试图将值异步提交给模板(通过AJAX),但没有使用该上下文呈现模板。

我将删除您的checkVal()函数的这一部分:

$.get(
    url="/passFails",
    data={'host' : myHost},
    success = function () {
        console.log('Data passed successfully!');
    }
);

并替换为:

window.location.href = "/passFails?" + $.param({"host": myHost});

正如@ guest271314所暗示的那样,这会将参数作为查询字符串发送,然后可以由模板进行解析。

根据评论更新

如果您必须使用“非AJAX” POST请求提交处理后的数据,则下面的方法应该有效。 这可能不是执行此操作的最佳方法,但是在不重构整个代码的情况下,这是使您的代码正常工作的最快方法。

步骤1:修改Results.html的表单标记

将您的表单标记更改为: <form name="ResultPage" method="" action=""> 换句话说,删除methodaction的值。

步骤2:修改script.jscheckVal()函数

更改您的checkVal()函数,如下所示:

function checkVal() {
    var myHost = [];
    var myPort = [];
    // Number of inputs to create
    var number = document.getElementById("Number").value;

    for (var i = 1; i <= number; i++) {

        //pass myHost and myPort to first.py for further processing.

        myHost.push(document.getElementById('Host ' + i).value);
        myPort.push(document.getElementById('Port ' + i).value);
    }

    for (var i = 0; i < number; i++) {

        alert("Value of Host: " + (i + 1) + " is: " + myHost[i]);
        alert("Value of Port: " + (i + 1) + " is: " + myPort[i]);
    }

    $(document.body).append('<form id="hiddenForm" action="/passFails" method="POST">' +
        '<input type="hidden" name="host" value="' + myHost + '">' +
        '<input type="hidden" name="port" value="' + myPort + '">' +
        '</form>');
    $("#hiddenForm").submit();
}

这基本上是处理用户输入数据的表单,将数据放入单独的隐藏表单,然后将该隐藏表单作为POST提交给服务器。

步骤3:修改pass_fails()app.py来访问数据。

pass_fails()方法中,将host_list变量的值更改为host_list = list(request.form["host"].split(",")) 这将读取“主机”的元组值,并将其从CSV字符串转换为列表。

这是修改后方法的完整版本:

@app.route('/passFails', methods=["POST", "GET"])
def pass_fails():
    host_list = list(request.form["host"].split(","))
    port_list = list(request.form["port"].split(","))

    print("Value of DATA variable in passFails Decorator is: %s" % host_list)

    for val in host_list:
        print("The value in VAL Variable is: %s" % val)

    return render_template('passFails.html', hosts=host_list)

暂无
暂无

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

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