简体   繁体   English

获取提交表单的操作

[英]get action of submitted form

I have the following code which is triggered every time a user submits a form on my site.我有以下代码,每次用户在我的网站上提交表单时都会触发该代码。

I want to modify it slightly, so that it checks the action of the submission, and based on the presence of a particular keyword, runs some code.我想稍微修改一下,以便它检查提交的操作,并根据特定关键字的存在运行一些代码。

My code is as follows:我的代码如下:

$("form").submit(function() {
    //do some generic stuff
    var formAction = ""; //get the action of the submitted form

    if (formAction.indexOf('keyword') !== -1) {
        //do some specific stuff for these forms
    }
});         

How do I get the action of the form which triggered this call?我如何获得触发此调用的formaction

$("form").submit(function() {
    //some stuff...

    //get form action:
    var formAction = $(this).attr("action");

    //some other stuff...
});   

if you need Javascript without jQuery:如果您需要没有 jQuery 的 Javascript:

var action=document.getElementById('formId').action

with jQuery:使用 jQuery:

var action=$('#formId').attr('action');

In JavaScript, you can use getAttribute method:在 JavaScript 中,您可以使用 getAttribute 方法:

var form = document.getElementById('register_form');
var action = form.getAttribute("action")

Note: form.getAttribute("action") is safer than using form.action.注意: form.getAttribute("action") 比使用 form.action 更安全。 Because if you have an input field named "action" within a form, then the browser can return that particular node instead of returning action URL of the form.因为如果表单中有一个名为“action”的输入字段,那么浏览器可以返回该特定节点而不是返回表单的操作 URL。

在此处输入图片说明

您可以通过这种方式获得动作属性 -

var formAction = $(this).attr("action");

In "vanilla" JS you have the Element.getAttribute()“vanilla” JS 中,你有Element.getAttribute()
Or (if needed) you could use the this.action .或者(如果需要)您可以使用this.action See below the slight difference看下面的细微差别

 document.querySelector("form").addEventListener("submit", function(e) { e.preventDefault(); // Prevents form from submitting console.log( this.getAttribute("action") ); // "test.php" console.log( this.action ); // <address>/test.php // this.submit(); // Submit afterwards or use AJAX to construct your request });
 <form action="test.php"> <input type="submit"> </form>

As michael-theriot already mentioned, most of the examples here ignore the fact that the submit element on the form could have a formaction of its own.正如michael-theriot已经提到的,这里的大多数示例都忽略了一个事实,即表单上的提交元素可以有自己的formaction

Following code takes this into account, while also working when there is only an action on the form itself too:下面的代码考虑到了这一点,同时在表单本身也只有一个动作时也能工作:

document.querySelector('form').addEventListener('submit', function(e) {
  e.preventDefault()
  console.log(e.submitter.formAction) // <address>/test.php
  
  // ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM