发送“表单数据”到AJAX调用

html part

<form id="custom_form" name="custom_upload" method="POST" enctype="multipart/form-data">
<label>Choose File:</label>
 <input id="in" name="csv_file" value="Add CSV" type="file" required />
<table class="opttable">
  <tr>
     <td>
         Title<span style="color: red;">*</span>
     </td>
     <td>
     <select id="select1" class="optselect form-control">
          <option>abc</option>
          <option>cde</option>                                                      
      </select>
      </td>
   </tr>
</table>
<input type="submit" value="Submit" class="onsubmit">
</form>

javascript part

$('.onsubmit').on('click', function (e) {
      var id = {{id}}
      var fd= $('form').serialize()
      console.log(fd)
      $.ajax({
       url: '/someview/'+id,
       type: 'POST',
       data: fd,
       sucess: function(data) {
       console.log(data);
       },
       error: function(err) {
         console.log('err: '+err);
       }
    });
});

This is my code. So basically I want to pass both file and normal data in ajax call. I think serialize method converts form data into strings and I want to send file as well so how can achieve this.

$('form').serialize() will give you array of objects like this

[
{"Name":"elementname","Value":"12"},
{"Name":"elementname2","Value":"hello"}
]

Either you can stringify the whole and send like this in

data: { "formData" :JSON.stringiy(fd)}

or

you can convert it into simple key value and send to sever as a JSON string

dataToSend={}

for(var v=0; v<fd.length;v++){
dataToSend[fd["Name"]] = fd["Value"]; 
}

and send in data as

data: { "formData":JSON.stringify(dataToSend)}

You can convert the data server side using

import json
json.loads(request.POST.get('formData'))

You can use FormData object and append the values you want to send to server.

You need csrf_token if you are making a post request. Store it in your html page. Try this:

<script>
    var CSRF_TOKEN = '{{ csrf_token }}';
</script>
$('.onsubmit').on('click', function (e) {
      e.preventDefault();
      var id = {{id}};
      var formData = new FormData();
      formData.append('csvFile', $('#in')[0].files[0]);
      formData.append('csrfmiddlewaretoken', CSRF_TOKEN);

    $.ajax({
       url : '/someview/'+id,
       type : 'POST',
       data : formData,
       processData: false,
       contentType: false,
       success : function(data) {
       },
       error: function(data){
       }
    });
});

In your views, you can get that file by

csv_file = request.FILES.get('csvFile')