javascript 通过Javascript提交带有参数的表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17789296/
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
Submit form with parameter through Javascript
提问by hari vallabh shukla
Below is my Javascript code where k and m are Javascript variables.
下面是我的 Javascript 代码,其中 k 和 m 是 Javascript 变量。
function javascriptfunction() {
document.forms[formname].action="gotopage.php?parameter1="+k+"¶meter2="+m;
document.forms[formname].submit();
}
The above code executes correctly when my HTML form has a POST method. Below is my HTML page:
当我的 HTML 表单具有 POST 方法时,上面的代码可以正确执行。下面是我的 HTML 页面:
<form name="formname" action=# method=POST>
<input type=text name="data1" value="one">
<input type=text name="data1" value="two">
<input type=button name="button1" value="send" onclick="javascritfunction();">
</form>
But when I give a GET method in my HTML form, then the HTML form data is submitted i.e
但是当我在我的 HTML 表单中给出一个 GET 方法时,则提交了 HTML 表单数据,即
gotopage.php?data1=one&data2=two is submitting not Javascript action value i.e
gotopage.php?parameter1="+k+"¶meter2="+m
So how to submit the form with Javascript parameter when the method is GET in the HTML form?
那么HTML表单中方法为GET时,如何提交带有Javascript参数的表单呢?
回答by Quentin
Submitting a GET form will replace the query string in the action with the form data.
提交 GET 表单将使用表单数据替换操作中的查询字符串。
Put the data in hidden inputs instead.
将数据放在隐藏输入中。
回答by davnicwil
In a GET request the form data has nowhere to 'go' other than in the query parameter string. So as Quentin points out, the query string gets automatically swapped out with the form field key value pairs. So you must use hidden fields to include extra data.
在 GET 请求中,除了查询参数字符串之外,表单数据无处可去。因此,正如 Quentin 指出的那样,查询字符串会自动与表单字段键值对换出。所以你必须使用隐藏字段来包含额外的数据。
In a POST request you've also got the query parameter string available, if you want to use it, but the form data gets inserted into the request payload (which a GET request does not have), so does not interfere with the query string. That's why you can customise the action url with whatever query string you like.
在 POST 请求中,如果您想使用它,您还可以获得查询参数字符串,但表单数据会插入到请求有效负载中(GET 请求没有),因此不会干扰查询字符串. 这就是为什么您可以使用您喜欢的任何查询字符串自定义操作 url。