拦截 JavaScript 中的表单提交,阻止正常提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5384712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:57:56  来源:igfitidea点击:

Intercept a form submit in JavaScript and prevent normal submission

javascripthtmlforms

提问by mrwooster

There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.

似乎有很多关于如何使用 javascript 提交表单的信息,但我正在寻找一种解决方案来捕获何时提交表单并在 javascript 中拦截它。

HTML

HTML

<form>
 <input type="text" name="in" value="some data" />
 <button type="submit">Go</button>
</form>

When a user presses the submit button, I do notwant the form to be submitted, but instead I would like a JavaScript function to be called.

当用户按下提交按钮时,我希望提交表单,而是希望调用 JavaScript 函数。

function captureForm() {
 // do some stuff with the values in the form
 // stop form from being submitted
}

A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.

一个快速的技巧是向按钮添加一个 onclick 功能,但我不喜欢这个解决方案......有很多方法可以提交表单......例如在输入时按下返回,这并没有说明。

Ty

回答by Michael McTiernan

<form id="my-form">
    <input type="text" name="in" value="some data" />
    <button type="submit">Go</button>
</form>

In JS:

在JS中:

function processForm(e) {
    if (e.preventDefault) e.preventDefault();

    /* do what you want with the form */

    // You must return false to prevent the default form behavior
    return false;
}

var form = document.getElementById('my-form');
if (form.attachEvent) {
    form.attachEvent("submit", processForm);
} else {
    form.addEventListener("submit", processForm);
}

Edit: in my opinion, this approach is better than setting the onSubmitattribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.

编辑:在我看来,这种方法比onSubmit在表单上设置属性更好,因为它保持了标记和功能的分离。但这只是我的两分钱。

Edit2: Updated my example to include preventDefault()

Edit2:更新了我的示例以包括preventDefault()

回答by mplungjan

You cannot attach events before the elements you attach them to has loaded

您无法在附加事件的元素加载之前附加事件

This works -

这有效 -

Plain JS

纯JS

DEMO

演示

Recommended to use eventListener

推荐使用 eventListener

window.addEventListener("load",function() {
  document.getElementById('my-form').addEventListener("submit",function(e) {
    e.preventDefault(); // before the code
    /* do what you want with the form */

    // Should be triggered on form submit
    alert('hi');
  });
});

but if you do not need more than one listener you can use onload and onsubmit

但如果您不需要多个监听器,您可以使用 onload 和 onsubmit

// Should only be triggered on first page load
alert('ho');

window.onload=function() {
    document.getElementById('my-form').onsubmit=function() {
    /* do what you want with the form */

    // Should be triggered on form submit
    alert('hi');
    // You must return false to prevent the default form behavior
    return false;
  }
}

jQuery

jQuery

// Should only be triggered on first page load
alert('ho');

$(function() {
  $('#my-form').on("submit",function(e) {
    e.preventDefault(); // cancel the actual submit

    /* do what you want with the form */

    // Should be triggered on form submit

    alert('hi');
  });
});

回答by kba

<form onSubmit="return captureForm()">that should do. Make sure that your captureForm()method returns false.

<form onSubmit="return captureForm()">应该这样做。确保您的captureForm()方法返回false.

回答by Vitaliy Borisok

Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests. These code should be added in the top of body element to create listener before any form rendered and submitted.

在 onload 无法帮助的情况下,处理我在实践中使用的所有请求的另一种选择是处理 javascript 提交、html 提交、ajax 请求。这些代码应该添加到 body 元素的顶部以在呈现和提交任何表单之前创建侦听器。

In example I set hidden field to any form on page on its submission even if it happens before page load.

在示例中,我将隐藏字段设置为提交时页面上的任何表单,即使它发生在页面加载之前。

//Handles jquery, dojo, etc. ajax requests
(function (send) {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    XMLHttpRequest.prototype.send = function (data) {
        if (isNotEmptyString(token) && isNotEmptyString(header)) {
            this.setRequestHeader(header, token);
        }
        send.call(this, data);
    };
})(XMLHttpRequest.prototype.send);


//Handles javascript submit
(function (submit) {
    HTMLFormElement.prototype.submit = function (data) {
        var token = $("meta[name='_csrf']").attr("content");
        var paramName = $("meta[name='_csrf_parameterName']").attr("content");
        $('<input>').attr({
            type: 'hidden',
            name: paramName,
            value: token
        }).appendTo(this);

        submit.call(this, data);
    };
})(HTMLFormElement.prototype.submit);


//Handles html submit
document.body.addEventListener('submit', function (event) {
    var token = $("meta[name='_csrf']").attr("content");
    var paramName = $("meta[name='_csrf_parameterName']").attr("content");
    $('<input>').attr({
        type: 'hidden',
        name: paramName,
        value: token
    }).appendTo(event.target);
}, false);

回答by rsplak

Use @Kristian Antonsen's answer, or you can use:

使用@Kristian Antonsen 的回答,或者您可以使用:

$('button').click(function() {
    preventDefault();
    captureForm();
});