Ajax发布FormData和表单 [英] Ajax post FormData and the form
本文介绍了Ajax发布FormData和表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这种形式:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<div class='col-sm-6' style="padding-left:0px;" >
<form action="/main/" method="post" id="my_form" enctype="multipart/form-data">
{% csrf_token %}
<br>
<div> <input type="text" name="description" id="id_description" /> </div>
<div> <input type="file" name="image" id="id_image" /> </div>
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<input class="btn btn-success" type="submit" name="submit" value="Gem" />
</form>
</div>
这将成功发送表单,并且在服务器端有效.但是我无法从服务器上的表单访问图像.
This successfully sends the form and it is valid on the server side. But I can´t access the image from the form on the server.
<script>
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
</script>
此解决方案发送带有图像文件的FormData,但是它不包含其他表单数据,并且该表单在服务器端无效:
This solution sends the FormData with the image file, but it does not include the other form data and the form is not valid on the server side:
<script type="text/javascript">
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData();
formData.append(
"image",
document.getElementById("id_image").files[0]
);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
</script>
是否可以同时发送文件和另一种形式的dara?
Is there a way to send both the file and the other form dara at the same time?
推荐答案
尝试将this
传递给FormData
.此外,您两次设置了type
.
Try passing this
to FormData
Also, you were setting type
twice.
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData(this);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
这篇关于Ajax发布FormData和表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文