我正在尝试将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 ????
答案 0 :(得分:0)
在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
功能
将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)