如何在ajax帖子上发送http正文数据

时间:2016-09-27 08:01:18

标签: jquery ajax http

$(document).delegate('form', 'submit', function(event) {
var $form = $(this);
var id = $form.attr('id');
// ...
  /* stop form from submitting normally */
  event.preventDefault();

//   /* get the action attribute from the <form action=""> element */
   var $form = $(this),
   url = $form.attr( 'action' );    

   var timeId = parseInt(id.substring(11));

   var formData = new FormData($("#"+id)[0]);
   console.log("time id of form is "+timeId);
   console.log(formData);
   $.ajax({
    url: url,
    method: "POST",
    dataType: 'json',
    data: formData,
    processData: false,
    contentType: false,
    success: function(result){},
    error: function(er){}
    });

});

我使用ajax post从html表单发送图像文件。如何作为此http帖子的正文发送其他数据

1 个答案:

答案 0 :(得分:0)

要从DOM元素传递其他数据,您也可以使用serialize()

$('form#id').serialize();

如果你想获得图像,你应该这样。

console.log($('#image').get(0).files[0]);

<input type="file" name="file" accept="image/*" id="image">

使用每个

可以追加多个文件
var data = new FormData();
$.each($('#image')[0].files, function(i, file) {
    data.append('file-'+i, file);
});

在formData

中传递附加数据
data.append("timeId",10000);

//Program a custom submit function for the form
$("form#test").submit(function(event){
  //disable the default form submission
  event.preventDefault();
  //Other data
  console.log($(this).serialize());
  //File data
  console.log($('#image').get(0).files);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype="multipart/form-data" id="test" method="post">
  <input type="text" name="firstname">
  <input type="text" name="lastname">
  <input type="hidden" name="id" value="10">
  
  <input type="file" name="file" id="image">
  <input type="submit">
</form>

相关问题