且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有两个提交jQuery的Ajax表单提交按钮

更新时间:2022-10-17 08:46:53

根据艾美特的回答,我对这种理想的修复只是杀表单的使用Javascript本身提交,像这样的:

  $(。vote_form)递交(函数(){返回false;});
 

这完全奏效。

有关完整,我的一些JS code在原岗位需要一点点的爱。比如,我增加了序列化功能的方式似乎并没有工作。该做的:

  $ form.serialize()+&放大器;提交=+ $(本).attr(价值)
 

下面是我的整个jQuery的code:

  $(。vote_form)递交(函数(){返回false;});
$(vote_up,.vote_down)。点击(函数(事件){
    $形式= $(本).parent(表);
    $。员额($ form.attr(行动),$ form.serialize()+&放大器;提交=+ $(本).attr(价值),功能(数据){
        //做一些与响应(数据)
    });
});
 

I have a form that looks like this:

<form action="/vote/" method="post" class="vote_form">
    <input type="hidden" name="question_id" value="10" />
    <input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" />
    <input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" />
</form>

When I bind to the form's submit ($("vote_form").submit()), I don't seem to have access to which image the user clicked on. So I'm trying to bind to clicking on the image itself ($(".vote_down, .vote_up").click()), which always submits the form, regardless of whether I try

  • return false;
  • event.stopPropogation(); or
  • event.preventDefault();

because all of those are form events.

  1. Should I attach my $.post() to the form.submit() event, and if so, how do I tell which input the user clicked on, or

  2. Should I attach my $.post() to the image click, and if so, how do I prevent the form from submitting also.

Here is what my jQuery code looks like now:

$(".vote_up, .vote_down").click(function (event) {
    $form = $(this).parent("form");
    $.post($form.attr("action"), $form.find("input").serialize() + {
        'submit': $(this).attr("value")
    }, function (data) {
        // do something with data
    });
    return false; // <--- This doesn't prevent form from submitting; what does!?
});

Based on Emmett's answer, my ideal fix for this was just to kill the form's submit with Javascript itself, like this:

$(".vote_form").submit(function() { return false; });

And that totally worked.

For completeness, some of my JS code in the original post need a little love. For example, the way I was adding to the serialize function didn't seem to work. This did:

    $form.serialize() + "&submit="+ $(this).attr("value")

Here's my entire jQuery code:

$(".vote_form").submit(function() { return false; });
$(".vote_up, .vote_down").click(function(event) {
    $form = $(this).parent("form");
    $.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
        // do something with response (data)
    });
});