передача списка фляг в HTML - PullRequest
       1

передача списка фляг в HTML

0 голосов
/ 24 февраля 2019

Я пытаюсь передать список Flask в HTML, но по какой-то причине на выходе получается пустая HTML-страница.ниже мой HTML и код Javascript, куда я отправляю список на Python:

<!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)

ниже приведен HTML-код, который должен напечатать список, отправленный с python, но все, что я получаю, этопустая страница.

<!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 ?????

1 Ответ

0 голосов
/ 24 февраля 2019

В вашей функции 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="">.Другими словами, удалите значения для method и action.

Шаг 2: Измените функцию checkVal() в script.js

Измените *Функция 1034 * выглядит следующим образом:

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(",")).Это прочитает значение кортежа для «host» и преобразует его из строки 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...