【发布时间】:2019-08-04 10:17:23
【问题描述】:
我通过一个下拉菜单创建了两个表单,其中一个具有接受文本的提交按钮,另一个具有接受文件的提交按钮(在我的情况下为图像)。我试图只使用一个 ajax post call 来发送任何一个数据。 我的意思是我的两个提交按钮都应该进行一次 Ajax 调用。有人可以帮我怎么做吗?
我的ajax调用是
$("#uploadImage").on("click", function(e) {
$("#addImgAlert").hide();
e.preventDefault();
var image = document.getElementById('file');
var formData = new FormData();
formData.append('image', image);
$.ajax({
enctype: 'multipart/form-data',
url: "<c:url value="/staff/module/slide/content?${_csrf.parameterName}=${_csrf.token}" />",
type: 'POST',
data: {
form: formData
},
processData: false,
contentType: false,
success: function(data) {
console.log("success");
console.log(data);
},
error: function(data) {
console.log("error");
console.log(data);
}
});
});
HTML
function addImage() {
$("#addImgAlert").show();
}
function addText() {
alert("inside add text");
$("#addTextAlert").show();
}
<button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Add</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<ul>
<li class="dropdown-item" id="addImage" onclick="addImage()">Add Image</li>
<li class="dropdown-item" id="addText" onclick="addText()">Add Text</li>
</ul>
</div>
<form name="photoForm" id="imageUploadForm" enctype="multipart/form-data" method="post">
<div id="addImgAlert" role="alert" style="cursor:move; width:340px; height: 130px; display:none; position: absolute;>
<h6><small>Upload Image: </small></h6>
<input type=" file " name="file " rows="5 " cols="500 " id="file " /><br>
<p class="mb-0 text-right "><button type="submit " id="uploadImage ">Upload Image</button>  
<button id="cancelBgImgBtn " type="button " class="btn light btn-xs ">Cancel</button></p>
</div>
</form>
<form name="textForm " id="textUploadForm " enctype="multipart/form-data " method="post ">
<div id="addTextAlert" role="alert " style="cursor:move; width:340px; height: 180px; display:none; position: absolute; top: 100px; right: 50px; z-index:999 ">
<h6><small>Enter Text: </small></h6>
<textarea class="form-control " id="textarea " rows="3 "></textarea>
<p class="mb-0 text-right "><button type="submit " id="submitText">Submit</button>  
<button id="cancelSubmitText " type="button " class="btn light btn-xs ">Cancel</button></p>
</div>
</form>
【问题讨论】:
-
您有两个带有提交按钮的表单,而您只希望它们使用一个 ajax?