【发布时间】:2012-01-26 19:41:57
【问题描述】:
如何使<a href="http://test/com/tag/test">Test</a> 像表单按钮一样工作?通过像表单按钮一样操作,我的意思是当单击链接以执行 method="get" 或发布时,以便能够通过获取或发布来捕获它。
不一定非得是一个链接,我可以适应以使它像那样工作!
【问题讨论】:
标签: javascript jquery post get hyperlink
如何使<a href="http://test/com/tag/test">Test</a> 像表单按钮一样工作?通过像表单按钮一样操作,我的意思是当单击链接以执行 method="get" 或发布时,以便能够通过获取或发布来捕获它。
不一定非得是一个链接,我可以适应以使它像那样工作!
【问题讨论】:
标签: javascript jquery post get hyperlink
如果您想使用链接提交表单:
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
如果您想在不离开页面的情况下提交表单,可以使用 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
请注意,.on() 是 jQuery 1.7 中的新功能,在这种情况下与使用 .bind() 相同。
【讨论】:
$.get() 函数与$.ajax({type:'get'}) 是一回事。我刚刚更新了我的$.ajax 代码以包含表单的数据,这可能非常重要:)
<form ....>
<a id="whatever" href="http://test/com/tag/test">Test</a>
</form>
假设您的表单中有任何带有 ID 的元素,您可以使用 jQuery 选择该 ID 并在其上附加一个 click 事件。在这种特殊情况下,它还将使用get 从/whatever.php 请求数据,您应该对其进行微调以同时使用get/post 并根据您的需要序列化表单数据。
$("#whatever").click(function(){
$.get("/whatever.php");
});
【讨论】:
<form...>吗?
$.get() 函数中添加$('form').serialize() 作为第二个参数:api.jquery.com/serialize
$.get() 没有刷新页面?
没有 jQuery
<form id="your_form">
<a href="javascript:{}" onclick="document.getElementById('your_form').submit(); return false;">submit</a>
</form>
【讨论】: