我有一个如下页面:
<html>
<head></head>
<body>
<form name="myform" action="http://www.example.com/page" method="post">
<input type="hidden" name="param1" value="1">
<input type="hidden" name="param2" value="2">
<input type="hidden" name="param3" value="3">
<input type="submit" value="Click Here If Not Redirect">
</form>
<script language="JavaScript">
document.myform.submit();
</script>
</body>
</html>
我想要一个JavaScript代码(没有jQuery或其他东西,轻量级在我的项目中非常重要)来执行上述操作(使用POST参数自动重定向页面)。我不希望用户看到重定向页面。例如:
<html>
<head>
<meta http-equiv="refresh" content="0; url=http://www.example.com/page">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
</head>
<body>
</body>
</html>
但当然有POST参数。
我的问题有解决办法吗?
答案 0 :(得分:2)
使用ajax发送表单
<html>
<head></head>
<body>
<form name="myform" id="myFormElement" action="http://www.example.com/page" method="post">
<input type="hidden" name="param1" value="1">
<input type="hidden" name="param2" value="2">
<input type="hidden" name="param3" value="3">
<input type="submit" onclick="submitAjax()">
</form>
<script language="JavaScript">
var form = document.getElementById("myFormElement");
function submitAjax() {
var data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.stackoverflow.com', true);
xhr.onload = function() {
// got a response for the post now redirect the user to
// "my portal... so I can do things in my portal...
// in the router's little web server."
window.location.href = "http://wherever.com/you/want/to/go/now";
console.log(this.responseText);
};
xhr.send(data);
}
form.onsubmit = function(e){
e.preventDefault();
submitAjax();
}
</script>
</body>
</html>