尝试将javascript数组传递给Python Flas

2024-10-03 21:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将一些javascript数组传递给Flask以设置模板页面,但在输出页面中得到的只是“在主机文本框中,您输入了:无”消息,下面是我的代码:

<!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="static/script.js"></script>
        <title>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="#" id="filldetails" onclick="addFields()">Enter Comms Details</a>
        <div id="container"/>
    </form>
    </body>
</html>

上面的代码调用下面的javascript函数:

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

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

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

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

    $.get(
        url="/passFails",
        data={host: myHost},
        success = function (data) {
            alert('page content: ' + data);
        }
    );
return true
}

javascript代码应该将数组/列表“myHost”传递给Python,但是由于某些原因,它没有传递错误消息。 python脚本如下

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 passFails():
    data = request.args.get('host')
    print("The Value in passFails is :%s " % data)
    return render_template('/passFails.html', Value=data)


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

最后,上面的python脚本应该将数据传递到最后一个HTML页面密码失败.html打印数组/列表中所有值的位置。 passFails页面如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>In the Host text box, you entered: {{Value}}</h1>

</body>
</html>

我只想知道为什么javascript部分的代码不能将列表传递给python,或者python脚本中是否有任何错误导致接收数组时出现问题? 任何帮助都将不胜感激。你知道吗


Tags: oftexthostnumberdatavaluevarcontainer
3条回答

.get更改为.getlist

request.args.getlist('host')

examples

和平

最后,我找到了答案,我所要做的就是在我的HTML文件中包含下面的script标记,让javascript使用$.get()函数将数据发送到python。这就是问题所在,问题得到了成功的解决:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

感谢你们分享你们的回答。你知道吗

如果在passFails中添加调试打印作为第一行,您将看到如下内容:

def passFails():
    print(request.args)
    # Out: ImmutableMultiDict([('host[]', '1'), ('host[]', '2'), ('host[]', '3')])

如前所述,您试图传递一些javascript数组,因此您的请求看起来像:

$.get(
    url="/passFails",
    data={host: [1,2,3]},
    success = function (data) {
        alert('page content: ' + data);
    }
);

它将被转换成一个请求url,比如:

http://localhost/passFails?host[]=1&host[]=2&host[]=3

因此,在host键上找不到您的值。为了让它工作,你可以使用^{}。另一个选项是在发送请求之前将数组中的myHost值序列化为JSON字符串,这样您就可以以request.args.get['host']的形式访问该值,但是您必须从Flask中的JSON表示反序列化它。你知道吗

相关问题 更多 >