我正在使用Ajax发布表单数据,但是单击提交按钮时出现错误。看来Ajax认为#img1
为空值。并且不会将文件输入值发送到操作。
错误消息:
Uncaught TypeError: Cannot read property 'length' of undefined at HTMLInputElement.<anonymous> (Room:403) at HTMLDocument.dispatch (jquery-3.3.1.min.js:2) at HTMLDocument.y.handle (jquery-3.3.1.min.js:2)
Ajax代码:
$(document).on('click', '#submitTheRoom', function (evt) {
evt.preventDefault();
var FileUpload = $("#img1").get(0);
var Files = FileUpload.Files;
var Data = new FormData();
for (var i = 0; i < Files.length; i++) {
Data.append('img1', Files[i]);
}
$('input, select').each(function (x,y) {
Data.append($(y).attr('name'), $(y).val());
});
$.ajax({
type: "post",
url: '@Url.Action("AddEditRoom", "Room", new { area = "Admin"})',
contentType: false,
processData: false,
data: Data
}).done(function (res) {
if (res.status === "success") {
alert(res.message);
} else {
alert("در ثبت اطلاعات مشکلی بوجود آمده. لطفا دوباره تلاش کنید");
}
}).fail(function (xhr, b, error) {
alert(error);
});
})
我的表单:
<form method="post" enctype="multipart/form-data">
@Html.AntiForgeryToken()
<input asp-for="Id" class="form-control hidden formInput" />
<div class="form-group myFormGroup col-lg-6 col-md-12">
<label asp-for="Name" class="col-lg-3 col-sm-3 control-label formLabel"></label>
<div class="col-lg-9 myInputContainer">
<input asp-for="Name" class="form-control formInput" />
</div>
<span asp-validation-for="Name" class="text-danger myError"></span>
</div>
<div class="form-group myFormGroup col-lg-6 col-md-12">
<label asp-for="Explanation" class="col-lg-3 col-sm-3 control-label formLabel"></label>
<div class="col-lg-9 myInputContainer">
<input asp-for="Explanation" class="form-control formInput" />
</div>
<span asp-validation-for="Explanation" class="text-danger myError"></span>
</div>
<div class="form-group myFormGroup col-lg-6 col-md-12">
<label asp-for="RoomImageOne" class="col-lg-3 col-sm-3 control-label formLabel"></label>
<div class="col-lg-9 myInputContainer">
<input id="img1" name="img1" type="file"
class="form-control formInput" asp-for="RoomImageOne" />
</div>
<span asp-validation-for="RoomImageOne" class="text-danger myError"></span>
</div>
<div class="modal-footer">
<input type="button" id="submitTheRoom" class="btn btn-success" value="submit">
</div>
</form>
答案 0 :(得分:0)
var Files = FileUpload.Files;
返回未定义。在控制台上检查FileUpload的值,并查看FileUpload.Files是否返回任何内容。试试
var Files = FileUpload.files;
相反。我怀疑大写字母可能是错字
答案 1 :(得分:0)
没有答案,我待会儿删除。
注释掉您的js并对此进行测试:
$(document).on('click', '#submitTheRoom', function(evt) {
evt.preventDefault();
var FileUpload = $("#img1").get(0);
console.log("FileUpload: " + FileUpload);
var Files = FileUpload.files; // lower case f.
console.log("Files: " + Files); // [object FileList]
console.log("Files.length: " + Files.length); // should be 0 on first load.
});
您得到相同的结果吗?不同吗?
将此添加到您的原始问题,然后在此处而不是在此处添加评论。如果没有用,我将其删除。