【问题标题】:Submit form upload with ajax and jquery使用ajax和jquery提交表单上传
【发布时间】:2017-03-03 02:28:41
【问题描述】:

有人可以帮助我使用 AJAX 提交表单吗?表单的目的是上传文件。我遇到的具体问题是如何捕获actionenctype 参数。我的表格:

<form role="form" method="post" action="http://localhost:3000/api/some_url" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input id="submit" type="submit" class="btn btn-primary" value="Submit">
</form>

我需要类似的东西:

$.ajax({

  type: "POST",
  url: 'http://localhost:3000/api/some_url',
  action: 'http://localhost:3000/api/some_url',
  enctype: 'multipart/form-data',
  headers: {
          'x-access-token': this.token,
  },
  success: function () {

    console.log('success!')
  },
  error: function (a, b, c) {
    console.log(a)
    console.log(b)
    console.log(c)
  }
})

有人可以帮忙吗?

提前致谢!

【问题讨论】:

  • 文件上传试试 dropzone.js,简单又好用

标签: jquery ajax forms upload


【解决方案1】:

为您的表单提供 id

<form id="frm_upload_image" role="form" method="post" action="http://localhost:3000/api/some_url" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input id="submit" type="submit" class="btn btn-primary" value="Submit">
</form>

之后在您的 ajax 调用中进行以下更改

var form = new FormData($("#frm_upload_image"));
   $.ajax({
        url: $("#frm_upload_image").attr('action'),
        type: "POST",                
        data: form,
        contentType: false,       
        cache: false,             
        processData:false,                                  
        success:function() {    
            console.log('success!')
        },
        error: function (a, b, c) {
            console.log(a)
            console.log(b)
            console.log(c)
        }
      });
});

对我有用

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 2012-07-05
    • 2013-06-22
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多