javascript 有没有办法在没有输入的情况下发送表单值

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

Is there a way of sending form values without inputs

javascriptjqueryhtmlforms

提问by einstein

Let say that I have the form below:

假设我有以下表格:

<form action="sendMessage.php" method="post">
    <label>Subject</label><input type="text"></input>
    <label>Message</label><input type="text"></input>
    <input type="submit"></input>
</form>

How can I send an another value like topic(which is pre-defined) without creating an another element for that? Is it possible or do I have to make input element and style it with display: none;

如何在不为此创建另一个元素的情况下发送另一个值,如主题(预定义)?是否有可能或者我必须制作输入元素并使用它的样式display: none;

The answer can contain html, javascript or jquery code.

答案可以包含 html、javascript 或 jquery 代码。

回答by Vivin Paliath

Use a hidden input element:

使用隐藏的输入元素:

<input type = "hidden" name = "topic" value = "something" />

回答by locrizak

use:

利用:

<input type='hidden' name='hidden_value' value='hidden' />

In you form you will either have access to $_GET['hidden_value']or $_POST['hidden_value']depending on your form method. The value of the variable will be hidden

在您的表单中,您将可以访问$_GET['hidden_value']$_POST['hidden_value']取决于您的表单方法。变量的值将是hidden

回答by Jeremy

<input type="hidden" name="topic" value="My Topic" />

回答by Johnny Brown

The way I've usually seen this done is: <input type="hidden" name="field_name" value="myValue" />

我通常看到这样做的方式是: <input type="hidden" name="field_name" value="myValue" />

回答by William

You can optionally use JQuery's ajax method when submitting your form:

提交表单时,您可以选择使用 JQuery 的 ajax 方法:

<form action="process_form">
    <button type="submit"></button>
</form>

<script>
$(form).submit(function(){
    var formdata = $(this).serialize()+"&var1=12&var2=24";

    $.ajax(function(){
        url: 'http://example.com/process_form'
        data: formdata,
        success: function(data){

            // do something nice here

        }
    });
});
</script>

This simply adds your form variables to the form data url string

这只是将您的表单变量添加到表单数据 url 字符串中