0

次のjQuery Ajaxコードがあります。

    $("#new_form").submit(function (event) {
        event.preventDefault();
        $.post("/home/new_ajax", $(this).serialize(), function (data) {
            if (data.errors == '') {
                $("#new_form").submit();
            } else {
                alert(data.errors);
            }
        }, "json");
    });

ただし、

event.preventDefault();

この行は機能しません:

 $("#new_form").submit();

これを回避する方法はありますか?

4

2 に答える 2

3

.trigger()代わりに使用.submit()できます。これにより、イベントハンドラーが利用できる追加のパラメーターを渡すことができます。

$("#new_form").submit(function (event, skipCustomStuff) {
    // If second parameter is truthy, let the submission happen
    if (skipCustomStuff) return;

    event.preventDefault();
    $.post("/home/new_ajax", $(this).serialize(), function (data) {
        if (data.errors == '') {
            // trigger submission passing in true as second parameter
            $("#new_form").trigger('submit', [true]);
        } else {
            alert(data.errors);
        }
    }, "json");
});
于 2012-11-05T21:56:31.043 に答える
1

これを行う最も簡単な方法は$("#new_form")[0].submit()、jQueryにバインドされたハンドラーをバイパスしてフォームを送信することです。

$("#new_form").submit(function (event) {
    event.preventDefault();
    $.post("/home/new_ajax", $(this).serialize(), function (data) {
        if (data.errors == '') {
            $("#new_form")[0].submit();
        } else {
            alert(data.errors);
        }
    }, "json");
});
于 2012-11-05T22:10:10.633 に答える