在使用Metro UI进行表单验证后,可以通过jQuery的AJAX方法提交表单。以下是一个基本的步骤和示例代码:
以下是一个简单的示例,展示了如何在Metro UI验证表单成功后,使用jQuery AJAX提交表单:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Metro UI Form with AJAX</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/metro-bootstrap@5.0.0/css/metro-bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/metro-bootstrap@5.0.0/js/metro.min.js"></script>
</head>
<body class="m-2">
<form id="myForm" data-role="validator" action="/submit" method="POST">
<div class="form-group">
<label>Email address</label>
<input type="email" class="form-control" name="email" data-validate="required email" placeholder="Enter email">
<span class="invalid-feedback">Please enter a valid email.</span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#myForm').on('submit', function(event) {
event.preventDefault(); // 阻止表单默认提交行为
if ($(this).data('role') === 'validator' && $(this).validator('validate')) {
// 表单验证通过
$.ajax({
url: $(this).attr('action'), // 表单提交的URL
type: $(this).attr('method'), // 提交方法
data: $(this).serialize(), // 序列化表单数据
success: function(response) {
alert('Form submitted successfully!');
console.log(response);
},
error: function(xhr, status, error) {
alert('An error occurred while submitting the form.');
console.error(error);
}
});
}
});
});
</script>
</body>
</html>
contentType: "application/json"
。通过以上步骤和代码示例,可以在使用Metro UI进行表单验证后,顺利地利用jQuery AJAX提交表单。
领取专属 10元无门槛券
手把手带您无忧上云