使用ajax和jquery

时间:2016-10-20 22:19:18

标签: jquery ajax forms upload

有人可以帮助我使用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)
  }
})

有人可以帮忙吗?

提前致谢!

1 个答案:

答案 0 :(得分:2)

为表单提供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)
        }
      });
});

它对我有用