javascript - 尝试将 javascript 数组传递给 Python Flask

标签 javascript python html flask

我试图将一些 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 页面 passFails.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脚本中是否有任何错误导致接收数组时出现问题? 任何帮助将不胜感激。

最佳答案

如果您将调试打印添加为 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);
    }
);

它会被转换(您可以并且完全应该在浏览器调试控制台中看到的内容)转换为如下请求网址:

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

因此,无法在 host 键上找到您的值。为了使它工作,你可以使用 request.args.getlist('host[]') 。另一种选择是在发送请求之前将 myHost 值从数组序列化为 JSON 字符串,以便您能够以 request.args.get['host']< 的形式访问值,但您必须从 Flask 中的 JSON 表示形式反序列化它。

关于javascript - 尝试将 javascript 数组传递给 Python Flask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54779550/

相关文章:

javascript - 同一 flatMap 方法中的多个 http 请求

c# - 将 List<int> 从 javascript 传递到 Controller

javascript - Vue.js v-if 逻辑条件问题

javascript - 如何使用子元素的 ID 选择父元素的第一个子元素?

html - 在网页上使用 Windows 95 字体

javascript - Jquery .css 不工作

python - 使用 pandas 在 Excel 文件中定义列

python - 如何在 Tensorflow Object Detection API v2 中同时训练和评估

python - 什么是 Linux 下软实时数据采集的良好存储候选者?

html - CSS - Dropbox 网站页脚效果?