如何使用AJAX向Flask中的视图发送数据?

发布于 2025-01-16 00:23:07 字数 2065 浏览 0 评论 0原文

请帮助...

我正在尝试上传 csv 或 excel 文件,并使用 Ajax 调用尝试将其与整数一起发送到 Flask。

HTML 表单:

<form id="testFileForm" method="POST" action="{{ url_for('auto') }}" enctype="multipart/form-data">
    {{ fileUploadForm.csrf_token }}
    <label class="connect choosefile setInput config-button-size " >
        <i class="fa fa-file" aria-hidden="true"></i>
        &nbsp; <span id="testFileLabel">Choose Test Data</span>
        {{ fileUploadForm.file(class="input1 btn btn-primary", id="testFile") }}

    </label>

    <label class="form-label" style="padding-left:10px ;">
        <input class="btn btn-primary config-button-size" id="testFilebtn" type="submit" value="Process">
    </label>
</form>

Ajax 调用:

$('#testFilebtn').click(function() {
                    
    var file = document.getElementById("testFile").files[0];
    alert(file)
    var data = {
      file: file,
      id : 1
    }
    alert('file loaded')
    $.ajax({
        data: data,
        type: "POST",
        url: "auto",
        "Content-Type": 'application/json',
        dataType: 'json',

        success: function(response) {
          alert(response)
        },
    });
  });

视图:

@app.route('/auto', methods=['POST', 'GET'])
@login_required
def auto(dataset_id=None):

    fileUploadForm = FileUploadForm()

    if request.method=='POST' and fileUploadForm.validate_on_submit():
        try:
            file = request.files['file']

            id = request.form['id']
            print('id')
            print(id)

        except UploadNotAllowed:
            return redirect(url_for("auto"))
        # return redirect(url_for("auto"))
        return "te"

检索 id 时出现错误,这表明我也没有从 ajax 调用接收文件。 错误:

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'id'

我是 Ajax 调用的新手,非常感谢您提供一些帮助...

Please help...

I am trying to upload a csv or excel file, and using an Ajax call trying to send it to Flask along with an integer.

HTML Form:

<form id="testFileForm" method="POST" action="{{ url_for('auto') }}" enctype="multipart/form-data">
    {{ fileUploadForm.csrf_token }}
    <label class="connect choosefile setInput config-button-size " >
        <i class="fa fa-file" aria-hidden="true"></i>
          <span id="testFileLabel">Choose Test Data</span>
        {{ fileUploadForm.file(class="input1 btn btn-primary", id="testFile") }}

    </label>

    <label class="form-label" style="padding-left:10px ;">
        <input class="btn btn-primary config-button-size" id="testFilebtn" type="submit" value="Process">
    </label>
</form>

Ajax Call:

$('#testFilebtn').click(function() {
                    
    var file = document.getElementById("testFile").files[0];
    alert(file)
    var data = {
      file: file,
      id : 1
    }
    alert('file loaded')
    $.ajax({
        data: data,
        type: "POST",
        url: "auto",
        "Content-Type": 'application/json',
        dataType: 'json',

        success: function(response) {
          alert(response)
        },
    });
  });

View:

@app.route('/auto', methods=['POST', 'GET'])
@login_required
def auto(dataset_id=None):

    fileUploadForm = FileUploadForm()

    if request.method=='POST' and fileUploadForm.validate_on_submit():
        try:
            file = request.files['file']

            id = request.form['id']
            print('id')
            print(id)

        except UploadNotAllowed:
            return redirect(url_for("auto"))
        # return redirect(url_for("auto"))
        return "te"

I get error while retrieving the id, which indicates I am also not receiving file from ajax call.
Error:

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'id'

I am new to Ajax calls, some help would highly be appreciated...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请帮我爱他 2025-01-23 00:23:07

我相信你可以这样做:

var fd = new FormData($('#testFileForm')[0]);    
fd.append( 'id', 1 );
$.ajax({
  url: 'http://example.com/',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

注意:

将 processData 设置为 false 可以防止 jQuery 自动将数据转换为查询字符串。
请参阅文档以获取更多信息。
将 contentType 设置为 false 是必须的,否则 jQuery 会错误地设置它。

I believe you could do it like this :

var fd = new FormData($('#testFileForm')[0]);    
fd.append( 'id', 1 );
$.ajax({
  url: 'http://example.com/',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

Notes:

Setting processData to false lets you prevent jQuery from automatically transforming the data into a query string.
See the docs for more info.
Setting the contentType to false is imperative, since otherwise jQuery will set it incorrectly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文