[英]How to send HTML form data to Python server using AJAX or similar?
我對此完全陌生,如果問題有點模糊,我深表歉意。 我需要知道從哪里開始。
我正在嘗試使用以下流程進行簡單設置:
我知道如何在前端和 python 中做所有事情。 我的問題是,如何將文件發送到服務器(將使用 GET 或 POST 等方式提交表單),我怎樣才能使這個像所附的圖表一樣? 任何指導表示贊賞。
我的前端代碼如下所示:
function sendfile(){ var file = document.getElementById("uploadfile").value; $.post('localhost:22222', //this is where I am hosting the server {SendData: file}, function(returnedArray) { var newData = //the response from python server, in array format; //set up different variables from the array //update the returned_info div with the new data }) }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> Upload your file here: <input type="file" id="uploadfile"> <button onclick="sendfile()">Submit!</button> </form> <div id="returned_info"> </div>
上面的代碼是否正確,或者有什么我可以改進的?
如何正確接收 python 服務器中的請求,以便它可以將 CSV 文件轉換為數組,像這樣? 服務器完成從這個原始數組獲取數據並進行計算后,我怎樣才能讓它將另一個數組發送回 HTML 頁面以供 jQuery 回調使用(參見代碼)?
我正在使用這個參考。
我假設您不使用 jQuery 並且僅使用純 JavaScript 構建它。
我使用render_template_string
而不是render_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)
編輯:帶有jQuery
的版本只需要更改HTML
中的<script>
。
@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>''')
順便說一句:在 Firefox JavaScript 中,當我嘗試使用alert(event)
或alert($("#my_form")[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.