如何使用AJAX或类似工具将HTML表单数据发送到Python服务器?
我对此一无所知,所以如果问题有点模糊,我深表歉意。我需要知道从哪里开始 我尝试使用以下流程进行简单设置:如何使用AJAX或类似工具将HTML表单数据发送到Python服务器?,python,ajax,http,server,webserver,Python,Ajax,Http,Server,Webserver,我对此一无所知,所以如果问题有点模糊,我深表歉意。我需要知道从哪里开始 我尝试使用以下流程进行简单设置: 用户将CSV文件上传到HTML表单,文件被发送(见下文)到 服务器 服务器正在运行一个python脚本,该脚本接受CSV和 将其转换为数组 python脚本在服务器上运行函数 数组并生成一个新的信息数组 此新阵列已发送 返回HTML网页,作为一个数组显示给用户 通过Javascript-DOM 我知道如何在前端完成所有工作,并使用python进行处理。我的问题是,如何将文件发送到服务器(表单
函数sendfile(){
var file=document.getElementById(“uploadfile”).value;
$.post('localhost:22222',//这是我托管服务器的地方
{SendData:file},
函数(返回数组){
var newData=//来自python服务器的响应,采用数组格式;
//从数组中设置不同的变量
//使用新数据更新返回的_info div
})
}
在此处上载您的文件:
提交
我假设您不使用jQuery,只使用纯JavaScript构建它
我使用render\u template\u string
而不是render\u template
只是为了简化测试-您可以将所有内容放在一个文件中并运行它
Url/
带有JavaScrip的显示表单,它使用XHR/AJAX
将文件发送到/upload
并获得结果
Url/upload
从表单中获取文件并生成HTML,其结果发送回浏览器
import os
from flask import Flask, request, render_template, render_template_string
from werkzeug.utils import secure_filename
import pandas as pd
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '.'
@app.route('/')
def index():
return render_template_string('''<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form id="my_form" method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="my_file" />
<input type="submit" id="my_button" value="Send" />
</form>
<div id="result"></div>
<script>
var my_form = document.getElementById("my_form");
var my_file = document.getElementById("my_file");
var my_button = document.getElementById("my_button");
var result = document.getElementById("result");
my_button.onclick = function(event){
var formData = new FormData(my_form);
formData.append('my_file', my_file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', '/upload', true);
xhr.addEventListener('load', function(e) {
// HTTP status message
//console.log(xhr.status);
// request.response will hold the response from the server
//console.log(xhr.response);
result.innerHTML = xhr.response;
});
xhr.send(formData);
event.preventDefault();
};
</script>
</body>
</html>''')
@app.route('/upload', methods=['POST'])
def upload():
#if request.method == 'POST': # no need if `methods=['POST']`
#if request.is_xhr(): # `is_xhr()` doesn't exist any more
# get file
#print(request.files)
temp_file = request.files.get('my_file') # `<input ... name="my_file">`
print(temp_file.filename)
# save it in
save_name = secure_filename(temp_file.filename)
full_path = os.path.join(app.config['UPLOAD_FOLDER'], save_name)
temp_file.save(full_path)
#data = pd.read_csv(full_path)
data = pd.DataFrame({
'Text': ['abc', 'def', 'ghi'],
'Number': [123, 456, 789],
})
print(data)
# convert dataFrame to HTML
table = data.to_html()
#table = data.to_html(classes="my_table", header=True)
# send generated HTML
return table
# or
# send template with embed HTML. It needs `|safe` to display HTML correctly
#return render_template_string('''DataFrame:</br>{{ table|safe }}</br>''', table=table)
if __name__ == '__main__':
app.run(debug=True)
顺便说一句:在Firefox中,当我尝试使用警报(事件)
或
alert($(“#我的表单”)[0])
能否提供有关python后端使用哪种框架的更多信息?例如,Django、Flask等。另外,您是否可以提供发送文件的HTML以及相关的后端代码?POST
可以发送更多数据。剩下的部分,您必须学习JavaScript或使用jQuery.post()
。对于服务器,AJAX请求与普通请求类似,所以没有区别——只是它不必发送完整的HTML,只需发送部分HTML或JSON数据,然后浏览器中的JavaScript必须获取并替换部分HTML。@MoonCheesez我添加了我的js和HTML代码。我将使用烧瓶,这是一个好的方式开始:?非常感谢。首先,您应该在不使用JavaScript的情况下检查并构建它,然后添加JavaScript。顺便说一句:您需要中的名称=
才能在烧瓶中访问它
谢谢!我可以看出这个文件设置对于测试是多么有用。如果我想将HTML文件分开保存,如果它在同一个目录中,那也行吗?如果你想将HTML保存在分开的文件中,那么你必须将它们放在子文件夹templates
中,因为它是Flask默认的模板文件夹。您只使用文件名而不使用文件夹名templates
-返回render\u template('index.html')
,或者如果您有templates/other/index.html
,那么render\u template('other/index.html')
我已经尝试过这个方法,它的工作方式正是我想要的。谢谢你的指导!
@app.route('/')
def index():
return render_template_string('''<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="my_form" method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" id="my_file" name="my_file" />
<input type="submit" id="my_button" value="Send" />
</form>
<div id="result"></div>
<script>
//$("#my_form").submit(function(event){
// or
$("#my_button").click(function(event){
$.post({
url: '/upload',
data: new FormData($("#my_form")[0]),
processData: false,
contentType: false, // Using FormData, no need to process data.
}).done(function(data){
$('#result').html(data);
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
event.preventDefault();
});
// warning: when I was using `alert(event)` or `alert($("#my_form")[0])` to see values in Firefox then code doesn't work
</script>
</body>
</html>''')