簡體   English   中英

如何使用 AJAX 或類似工具將 HTML 表單數據發送到 Python 服務器?

[英]How to send HTML form data to Python server using AJAX or similar?

我對此完全陌生,如果問題有點模糊,我深表歉意。 我需要知道從哪里開始。

我正在嘗試使用以下流程進行簡單設置:

  1. 用戶將 CSV 文件上傳到 HTML 表格,文件被發送(見下文)到服務器。
  2. 服務器正在運行 python 腳本,該腳本采用 CSV 並將其轉換為數組。
  3. python 腳本在數組上運行函數並創建一個新的信息數組。
  4. 這個新數組作為數組發送回 HTML 網頁,該數組將通過 Javascript DOM 顯示給用戶。

我知道如何在前端和 python 中做所有事情。 我的問題是,如何將文件發送到服務器(將使用 GET 或 POST 等方式提交表單),我怎樣才能使這個像所附的圖表一樣? 任何指導表示贊賞。

20 年 5 月 10 日編輯

我的前端代碼如下所示:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM