我有一种情况,我在我的应用程序的页面上多次使用相同的表单,允许用户编辑或删除数据但是当使用下面的javascript来监听表单提交时页面只是刷新。
我打算使用$('.service_form').serialize()
提交表单,但是这样做时它会从页面上的每个表单序列化值并完成ajax请求,但是如果我使用$(this).serialize()
页面只是刷新。< / p>
HTML表单
<div id="service_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form class="service_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class='form-group has-feedback has-feedback-left'>
<label for="service_idno">IDNO:</label>
<input type="text" class="form-control required" id="service_idno" name="service_idno">
</div>
<div class='form-group has-feedback has-feedback-left'>
<label for="service_code">Service Code:</label>
<input type="text" class="form-control required" id="service_code" name="service_code">
</div>
<div class='form-group has-feedback has-feedback-left'>
<label for="service_cost">Service Cost:</label>
<input type="number" class="form-control required" id="service_cost" name="service_cost">
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Commit" class="btn btn-success" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
的Javascript
$('.service_form').each(function(){
$(this).validate({
errorClass: 'validation-error-label',
highlight: function(element, errorClass) {$(element).removeClass(errorClass);},
errorPlacement: function(error, element){if (element.parents('div').hasClass('has-feedback')) {error.appendTo(element.parent() );}},
rules:{vali: "required"},
messages: {
service_idno: {required: "* Service IDNO Is Required."},
service_code: {required: "* Service Code Is Required."},
service_name: {required: "* Service Name Is Required."},
service_account: {required: "* Account Is Required."},
service_cost: {required: "* Cost Is Required."},
service_retail: {required: "* Retail Is Required."},
},
submitHandler: function(form) {
$.ajax({
url: "rest/servicedelete.php",
type: "POST",
data: $(this).serialize(),
timeout:9000,
beforeSend:function() {
$('.modal').modal('hide');
},
success: function (data) {
},
error:function() {
$('#notification').html('Remote Service Currently Unavailable');
},
});
}
});
});
我希望能够随时在网页上提交任何表单,并且只提交该数据。
答案 0 :(得分:6)
submitHandler()
的范围不是表单元素,因此this
不是您所期望的。请改用提供的form
参数:
data: $(form).serialize(),
答案 1 :(得分:1)
首先,您需要将当前表单存储在像
这样的临时变量中 $('.service_form').each(function(){
var form = $(this);
然后你像
那样进行序列化 data: $(form).serialize(),
这将解决您的问题。