jQuery 通过 Ajax 提交模态表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22759087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submitting modal form via Ajax
提问by schizoskmrkxx
I have a normal form for my question entity.
我的问题实体有一个标准形式。
Within that form is a modal form which allows users to add additional tags for their question.
该表单中有一个模态表单,允许用户为他们的问题添加其他标签。
Here is an image of my modal form:
这是我的模态形式的图像:
Here is my twig template for my modal form:
这是我的模态表单的树枝模板:
<div id="mymodal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add New Tag</h4>
</div>
<form class="tagForm" id="tag-form" action="{{ path('addTag') }}" method="post" enctype="multipart/form-data">
<div class="modal-body">
<label for="tagName">Tag Name: </label>
<input id="tagName" class="form-control" type="text"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input id="tag-form-submit" type="submit" class="btn btn-primary" value="Add Tag">
</div>
</form>
</div>
</div>
Script for viewing my modal form:
查看我的模态表单的脚本:
$('#addTag').click(function(e) {
e.preventDefault();
$('#mymodal').modal();
});
Script for my modal form submission:
我的模态表单提交脚本:
$(function() {
$('#tag-form').submit(function() {
$.ajax({
type: "POST",
url: "{{ path('addTag') }}",
data: $('form.tagForm').serialize(),
success: function(response) {
alert(response['response']);
},
error: function() {
alert('Error');
}
});
return false;
});
});
My problem is that everytime I click the add tag button, all the forms including the question form is also submitted.
我的问题是,每次单击添加标签按钮时,包括问题表单在内的所有表单也会被提交。
What I really want is just to submit the modal form.
我真正想要的只是提交模态表单。
采纳答案by David Hirst
It looks like your firing this on the submit event, which is why its....submitting? Maybe this would work better?
看起来你在提交事件上触发了这个,这就是为什么它......提交?也许这会更好?
$(function() {
$('#tag-form-submit').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "{{ path('addTag') }}",
data: $('form.tagForm').serialize(),
success: function(response) {
alert(response['response']);
},
error: function() {
alert('Error');
}
});
return false;
});
});