jQuery $.post 不传递按下的按钮
最近我遇到了一个问题,即 $.post 不发送有关按下的按钮的信息。 即我们有一个带有两个按钮的表单。
<form method="post" action="/home/index">
<input type='hidden' name='data1' value='value1' />
<button name="button1" type="submit">First</button>
<button name="button2" type="submit">Second</button>
</form>
$(document).ready(function() {
$('#formId').submit(function () {
var f = $(this);
var action = f.attr("action");
var serf = f.serialize();
$.post(action, serf,
//onreturn
function (data) {
//do something here on success
},
'json'
);
return false;
});
});
如果用户按下第一个按钮,没有 ajax 的表单将按如下方式发布:data1=value1&button1
但是当我使用 $.post 发布的表单时,不包含有关按钮的任何信息:data1=value1 strong>
jQuery 1.6.1
行为取决于按下的按钮。 任何帮助或解决方法将不胜感激!
Recently I've stuck with a problem where $.post does not send information about button which were pressed.
I.e. we have a form with two buttons.
<form method="post" action="/home/index">
<input type='hidden' name='data1' value='value1' />
<button name="button1" type="submit">First</button>
<button name="button2" type="submit">Second</button>
</form>
$(document).ready(function() {
$('#formId').submit(function () {
var f = $(this);
var action = f.attr("action");
var serf = f.serialize();
$.post(action, serf,
//onreturn
function (data) {
//do something here on success
},
'json'
);
return false;
});
});
Without ajax form is posted as following if user pressed First button: data1=value1&button1
But when I use $.post posted form does not contain any information about button: data1=value1
jQuery 1.6.1
The behavior depends on that which button were pressed.
Any help or workaround would be appriciate!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您要停止浏览器的默认行为(即提供按钮值的行为),因此您必须捕获按下的按钮,并将该信息添加到您发布的数据中(您的
serf
数据)。也许最可靠的方法是挂钩按钮上的click
事件以及表单的submit
事件,并将它们全部路由到执行以下操作的中央函数:使用(或不使用)按钮值的 ajax 提交(在以另一种方式提交表单的情况下,不使用按钮值,而不是按其中一个按钮)。沿着这些思路:
Since you're stopping the browser's default behavior, which is what supplies the button value, you'll have to capture what button was pressed, and add that information to the data you're posting (your
serf
data). Probably the most reliable way would be to hook theclick
event on the buttons as well as thesubmit
event of the form, and route them all to a central function that does the ajax submission with (or without) a button value (without in the case of a form submitted another way, rather than by pressing one of those buttons).Something along these lines:
我认为这不会发生。但无论如何,你也可以做这样的事情。
I don't think that is suppose to be happening. But anyways, you could something like this too.