jQuery 获取提交表单的操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16087018/
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-26 16:23:55  来源:igfitidea点击:

get action of submitted form

javascriptjquery

提问by Elie

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 actionof the formwhich triggered this call?

我如何获得actionform,其触发这个电话?

回答by Adriano Carneiro

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

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

    //some other stuff...
});   

回答by Luca C.

if you need Javascript without jQuery:

如果您需要没有 jQuery 的 Javascript:

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

with jQuery:

使用 jQuery:

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

回答by Mohammad Adil

You can get action attr this way -

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

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

回答by Rusty

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. 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.

注意:form.getAttribute("action") 比使用 form.action 更安全。因为如果表单中有一个名为“action”的输入字段,那么浏览器可以返回该特定节点而不是返回表单的操作 URL。

enter image description here

在此处输入图片说明

回答by Roko C. Buljan

In "vanilla"JS you have the Element.getAttribute()
Or (if needed) you could use the this.action. See below the slight difference

“vanilla”JS 中,你有Element.getAttribute()
Or(如果需要)你可以使用this.action. 看下面的细微差别

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>