如果您想使用链接提交表单:
HTML --
<form action="my-page.php" id="my-form" method="post">...</form>
<a href="#" id="form-submit">SUBMIT</a>
JS --
$(function () {
$('#form-submit').on('click', function () {
//fire the submit event on the form
$('#my-form').trigger('submit');
//stop the default behavior of the link
return false;
});
});
文档用于trigger()
: http://api.jquery.com/trigger http://api.jquery.com/trigger
如果您想在不离开页面的情况下提交表单,可以使用 AJAX 调用:
$(function () {
$('#form-submit').on('click', function () {
//cache the form element for use later
var $form = $('#my-form');
$.ajax({
url : $form.attr('action') || '',//set the action of the AJAX request
type : $form.attr('method') || 'get',//set the method of the AJAX reqeuest
data : $form.serialize(),
success : function (serverResponse) {
//you can do what you want now, the form has been submitted, and you have received the serverResponse
alert('Form Submitted!');
}
});
});
$('#my-form').on('submit', function () {
//stop the normal submission of the form, for instance if someone presses the enter key inside a text input
return false;
});
});
文档用于$.ajax()
: http://api.jquery.com/jquery.ajax http://api.jquery.com/jquery.ajax
注意.on()
是 jQuery 1.7 中的新功能,在本例中与使用相同.bind()
.