当我的表单操作指向另一个页面时,我想从当前页面获取post值。以下是代码示例:
<form id="form1" name="form1" action='page2.php' method="post">
<input type="text" id="test" name="test" value="<?php echo 'test'; ?>" />
<input type='submit' value='submit' />
</form>
//i want to get the value here but it's not working because all value pass to page2.php
$value = $_POST['test'];
echo $value;
建议我如何表演这些家伙!
您可以在表单的onsubmit
属性中使用JavaScript拦截表单提交。然后您可以对第二个提交位置进行AJAX调用。
如果您想取消表单提交,请使用return false;
完成JavaScript
以下是它可能的样子:
<form method="POST" action="page2.php" onsubmit="submit(this)"> ... </form>
然后在您的JavaScript中:
function submit(form) {
var ajax = new XMLHttpRequest();
ajax.open("POST", "page1.php");
ajax.send(new FormData(form));
}
您可能会发现这个源代码有助于在AJAX中发送FormData
对象。
或者,jQuery使AJAX调用变得非常简单。
function submit(form) {
$.post("page1.php", $(form).serialize());
}
下面是一个使用AJAX将表单数据发送到文件并执行该文件的示例,而客户端无需刷新或重定向到不同的页面。
function submit() {
var v = document.getElementById("1234").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//inserts output from file into given location
//in this case, a div with id of 'content'
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "upload.php?data="+v, true);
xmlhttp.send();
}
还有一些方法可以使用JQuery(如何在不重新加载页面的情况下选择文件提交表单?)