我想用ajax提交我的模态表单。首先,我填写表格中的一些预定义数据。这部分有效。但是,当我单击提交按钮时,我的form.php脚本会受到影响,但在脚本中,$ _POST为空。我在这里做错了什么?
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Edit MAC alias</h4>
</div>
<div class="modal-body">
<form class="macalias" name="macalias" id="macalias">
<input type="hidden" class="form-control" id="valmac" name="valmac">
<div class="form-group">
<label for="message-text" class="control-label">Alias:</label>
<input type="text" class="form-control" id="valalias" name="valalias">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$(function ()
{
// fill the form with data (this part works)
$('#exampleModal').on
('show.bs.modal', function (event)
{
var button = $(event.relatedTarget)
var valmac = button.data('valmac')
var valalias = button.data('valalias')
var modal = $(this)
modal.find('.modal-title').text('Edit alias for ' + valmac)
modal.find('.modal-body input[id=valmac]').val(valmac)
modal.find('.modal-body input[id=valalias]').val(valalias)
}
)
$( ".macalias" ).submit(function( event ) {
//cancel the default submit action by calling
event.preventDefault();
$.ajax({
type: "POST",
url: "form.php",
data: $('form#macalias').serialize(),
success: function(msg){
$('#exampleModal').modal('hide')
},
error: function(){
alert("failure");
}
});
});
});
</script>
编辑:代码现在可以使用
答案 0 :(得分:1)
你的表单有一个名为macalias的类,所以它应该是
data: $('form.macalias').serialize()
编辑!
您可以收听按键(回车),但我认为为表单提交附加事件处理程序会更好。取代
$("input#submit").click(function(){...});
与
$( ".macalias" ).submit(function( event ) {
//cancel the default submit action by calling
event.preventDefault();
//Your ajax stuff
});
并切换到提交按钮
<button type="submit" class="btn btn-default" data-dismiss="modal" >Close</button>