要使用 AJAX 发送带有文件的表单而不重新加载页面,您需要使用
FormData
来正确处理文件上传。
<form id="settings" method="POST" enctype="multipart/form-data">
<!-- Other form fields -->
<input type="file" id="logo" name="logo" accept="image/png, image/jpeg, image/gif">
<button type="submit" id="send" class="btn btn-primary">Save</button>
</form>
$(document).ready(function() {
$('#settings').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: '/settings',
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
success: function(response){
alert('Form submitted successfully!');
// Handle the response from the server
},
error: function(){
console.log('Error occurred!');
}
});
});
});