我在用AJAX上传图像时遇到问题。 当我单击“发送图像”时,我收到一个jQuery反馈,告诉我在单击图像时“未定义”
我尝试了另一种可以正常工作的方法,但是创建了一个非常简单的表单,并通过将class属性赋予jquery而不是id。 那行得通..
不起作用的表格(我希望它起作用:))
<form action="ajax/uploadimage.php" method="post" enctype="multipart/form-data" >
<div class="card-body">
<!-- Single -->
<div class="dropzone dropzone-single mb-3" data-toggle="dropzone" data-dropzone-url="http://">
<div class="custom-file">
<input id="file-upload" type="file" name="fileToUpload" class="custom-file-input" multiple required>
<label class="custom-file-label" for="file-upload">Choose file</label>
</div>
<div class="dz-preview dz-preview-single">
<div class="dz-preview-cover">
<img class="dz-preview-img" src="..." alt="..." data-dz-thumbnail>
</div>
</div>
</div>
<center><input type="submit" class="btn btn-primary" id="file-submit" value="<?php echo TXT_DASHBOARD_MODIFIER; ?>"></center>
</div>
</form>
不起作用的jQuery
<script type="text/javascript">
$(function() {
$('#file-submit').on('click', function() {
var file_data = $('#file-upload').prop('files')[0];
if(file_data != undefined) {
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: 'ajax/uploadimage.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
if(response == 'success') {
alert('File uploaded successfully.');
} else if(response == 'false') {
alert('Invalid file type.');
} else {
alert('Something went wrong. Please try again.');
}
$('#file-upload').val('');
}
});
}
return false;
});
});
</script>
工作方式:
<form>
<input type="file" name="image" class="image" required>
<input type="submit" name="submit" class="submit" value="Submit">
</form>
起作用的jquery:
<script type="text/javascript">
$(function() {
$('.submit').on('click', function() {
var file_data = $('.image').prop('files')[0];
if(file_data != undefined) {
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: 'ajax/uploadimage.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
if(response == 'success') {
alert('File uploaded successfully.');
} else if(response == 'false') {
alert('Invalid file type.');
} else {
alert('Something went wrong. Please try again.');
}
$('.image').val('');
}
});
}
return false;
});
});
</script>
我想解决未定义的错误。 感谢您的帮助:)