如何使用AJAX或类似方法将HTML表单数据发送到Python服务器?

问题描述 投票:0回答:1

对于这个问题,我有点陌生,所以我很陌生。我需要知道从哪里开始。

我正在尝试通过以下流程进行简单设置:

  1. 用户将CSV文件上传到HTML表单,文件发送到(参见下文)服务器。
  2. 服务器正在运行使用CSV和将其转换为数组。
  3. Python脚本在数组并生成新的信息数组。
  4. 此新数组已发送返回到HTML网页的数组将显示给用户通过Javascript DOM。

我知道如何在前端和python中进行处理。我的问题是,如何将文件发送到服务器(将使用GET或POST等方式提交表单),如何使它像附图所示?任何指导表示赞赏。

编辑5/10/20

我的前端代码如下:

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文件转换为数组,例如this?服务器完成数据获取并从该原始数组进行计算后,如何将另一个数组发送回HTML页面以供jQuery回调使用(请参见代码)?

我正在使用this参考。

enter image description here

python ajax http server webserver
1个回答
0
投票

我假设您不使用jQuery,而仅使用纯JavaScript进行构建。

我使用render_template_string而不是render_template只是为了简化测试-您可以将所有文件放在一个文件中并运行它。

带有JavaScrip的URL /显示表单,它使用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

EDIT:版本仅需要在<script>中的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>''')
© www.soinside.com 2019 - 2024. All rights reserved.