Javascript 如何使用javascript在POST方法中发送数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13678358/
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
how to send data in POST method using javascript
提问by raju
In javascript normaly page redirection can be done as follow with a parameter.
在 javascript 中,正常页面重定向可以通过参数完成,如下所示。
window.location = "add-new-cos.jsp?id="+id;
but this id value is send to the next page with in the GET method. but i want to send it with the POST method. is there any way to do it with javascript....?
但是这个 id 值通过 GET 方法发送到下一页。但我想用 POST 方法发送它。有什么办法可以用javascript做到这一点....?
回答by Andreas
Not as easy as the window.locationredirect but easy enough :)
不像window.location重定向那么容易,但足够简单:)
var form = document.createElement("form");
input = document.createElement("input");
form.action = "add-new-cos.jsp";
form.method = "post"
input.type = "hidden";
input.name = "id";
input.value = id;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
回答by Just_Mad
Sending POST data is avaliable either on submitting form or via ajax request. You may try to create an invisible form with hidden fields with correct names and values and submit it by javascript when needed.
发送 POST 数据可以在提交表单时或通过 ajax 请求发送。您可以尝试使用具有正确名称和值的隐藏字段创建一个不可见的表单,并在需要时通过 javascript 提交它。
回答by Chris Li
You can put the id in a form, use document.forms["myform"].submit();and returns a redirect action in your request handler on server.
您可以将 id 放入表单中,document.forms["myform"].submit();在服务器上的请求处理程序中使用并返回重定向操作。
回答by Moorthy GK
Using window.location.href it's not possible to send a POST request.
使用 window.location.href 不可能发送 POST 请求。
What you have to do is to set up a form tag with data fields in it, set the action attribute of the form to the URL and the method attribute to POST, then call the submit method on the form tag.
你要做的就是设置一个包含数据字段的表单标签,将表单的action属性设置为URL,将method属性设置为POST,然后调用表单标签上的submit方法。

