可能重复:
JavaScript post请求类似于表单提交
我在JS中计算了一个值,我想将其作为输入表单的一部分传递给PHP脚本。如何将JS值作为POST参数传递给PHP?
基本上,在提交时,我需要将total
变量通过post传递给下一个脚本。
首先想到的方法是创建一个不可见的输入表单,其中包含该值,并与表单一起输入,这种方法可行吗?
可能重复:
JavaScript post请求类似于表单提交
我在JS中计算了一个值,我想将其作为输入表单的一部分传递给PHP脚本。如何将JS值作为POST参数传递给PHP?
基本上,在提交时,我需要将total
变量通过post传递给下一个脚本。
首先想到的方法是创建一个不可见的输入表单,其中包含该值,并与表单一起输入,这种方法可行吗?
有很多方法可以实现这个目标。就你提问的方式而言,可以使用隐藏的表单元素。
在你的表单中创建这个表单元素:
<input type="hidden" name="total" value="">
那么你的表单应该像这样:
<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>
那么你的JavaScript代码可能是这样的:
<script>
function setValue(){
document.sampleForm.total.value = 100;
document.forms["sampleForm"].submit();
}
</script>
是的,您可以使用一个 <input type="hidden" />
,并在您的 JavaScript 代码中设置该隐藏字段的值,以便它随其他表单数据一起提交。
function ajax(elementID,filename,str,post)
{
var ajax;
if (window.XMLHttpRequest)
{
ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
}
else if (ActiveXObject("Microsoft.XMLHTTP"))
{
ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
}
else if (ActiveXObject("Msxml2.XMLHTTP"))
{
ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
}
else
{
alert("Error: Your browser does not support AJAX.");
return false;
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4&&ajax.status==200)
{
document.getElementById(elementID).innerHTML=ajax.responseText;
}
}
if (post==false)
{
ajax.open("GET",filename+str,true);
ajax.send(null);
}
else
{
ajax.open("POST",filename,true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(str);
}
return ajax;
}
第一个参数是您要更改的元素。第二个参数是您正在加载到更改的元素中的文件名。第三个参数是您正在使用的GET或POST数据,例如“total=10000&othernumber=999”。最后一个参数为true表示您要使用POST,false表示您要使用GET。
<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>
<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>
当然,这将把位置更改为 script.php
。 如果您想对用户进行不可见的更改,您需要使用 AJAX。以下是一个 jQuery 的例子(简化版)。不需要表单或隐藏输入。
$.post("script.php", { total: getTotalFromSomewhere });
$_POST['element']
还是从 $_POST['getTotalFromSomewhere']
中访问? - Oliver$_POST['total']
。 - Phil