我正在尝试使用Form
提交HTML Ajax
,但我没有获得任何警报成功或失败。
的index.html
<form method="post" class="needs-validation" enctype="multipart/form-data" action="/upload/" id="fupload">
<div class="custom-file">
<input type="file" class="custom-file-input" id="data_files" name="data_files" multiple required>
<label class="custom-file-label" for="data_files">Choose files</label>
</div>
<button type="submit">Upload files</button>
</form>
<script type="text/javascript">
var frm = $('#fupload');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('Form Submitted');
},
error: function(data) {
alert('Form submission failed');
}
});
return false;
});
views.py
@csrf_exempt
def upload(request):
if request.method == 'POST':
return HttpResponse()
任何猜测为什么它不起作用
答案 0 :(得分:1)
尝试更改以下内容:
action
。将按钮更改为type="button"
并添加事件监听器
<form method="post" class="needs-validation" id="fupload">
<div class="custom-file">
<input type="file" class="custom-file-input" id="data_files" name="data_files" multiple required>
<label class="custom-file-label" for="data_files">Choose files</label>
</div>
<button type="button" id="upload-files-btn">Upload files</button>
</form>
<script type="text/javascript">
var frm = $('#fupload');
var btn = $('#upload-files-btn');
btn.bind('click', handleClick);
var formData = new FormData(); // Use FormData instead
formData.append('file', frm.files[0], frm.files[0].name) // The first argument is the 'key' of the form data so change it to whatever works.
var handleClick = function (event) {
event.preventDefault();
$.ajax({
type: frm.attr('method'),
url: '/upload/',
data: formData,
contentType: false, // add this to indicate 'multipart/form-data'
success: function (data) {
alert('Form Submitted');
},
error: function(data) {
alert('Form submission failed');
}
});
}
</script>