使用ajax和jquery提交表单上传

时间:2022-11-24 12:58:12

Can someone help me submit a form using AJAX? The purpose of the form is to upload a file. The specific problem I'm having is how to capture the action and enctype parameters. My form:

有人能帮我用AJAX提交表单吗?表单的目的是上传一个文件。我遇到的具体问题是如何捕获操作和封装类型参数。我的表格:

<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>

I need something like:

我需要类似:

$.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)
  }
})

Can someone help?

有人可以帮忙吗?

Thanks in advance!

提前谢谢!

1 个解决方案

#1


2  

Give id to your form

把身份证给你的表格。

<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>

after that make following changes in your ajax call

然后在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)
        }
      });
});

it works for me

它适合我

#1


2  

Give id to your form

把身份证给你的表格。

<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>

after that make following changes in your ajax call

然后在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)
        }
      });
});

it works for me

它适合我