我有一个看起来像这样的表格。
<form name="myform" action="selectPlayer.php">
<select name="forward" onchange="javascript:submitform(top);">
<option value="-">-------</option>
<option id="forwardAdd" value="add">Add</option>
<option id="forwardChange" value="change">Change</option>
</select>
<select name="center" onchange="javascript:submitform(mid);">
<option value="-">-------</option>
<option id="centerAdd" value="add">Add</option>
<option id="centerChange" value="change">Change</option>
</select>
</form>
我正在将表单提交到selectPlayer.php。在此页面上,我需要知道此人是要添加玩家还是在每个选择元素指定的位置更改玩家。换句话说,如果玩家想将科比·布莱恩特添加到其阵容的中心位置,我需要在selectPlayer.php中为此设置变量。
这是一个使用Javascript的简单文档提交功能,如下所示:
<script type="text/javascript">
function submitform(var position)
{
if(document.myform.onsubmit &&
!document.myform.onsubmit())
{
return;
}
document.myform.submit()
}
</script>
我应该在脚本中输入什么以将这些变量传递到下一个php页面?
最佳答案
在php页面的$ _POST变量下获取选择,并在表单中添加method = "post"
。
例如。 $ _POST ['forward']将在此页上的此表单中提供在正向选择中选择的选项!
更新:
您的表格
<form name="myform" action="selectPlayer.php" method = "post">
<select name="forward" id="forward">
<option value="-">-------</option>
<option id="forwardAdd" value="add">Add</option>
<option id="forwardChange" value="change">Change</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
selectPlayer.php
<?php
if(isset($_POST['forward'])){
echo "OK";
}
?>
更新2:
重要的是将jquery文件附加到您的form.php
form.php
<html>
<head>
<script src="jquery-1.9.0.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#name', function() {
//var element = $(this); //USE THESE IN CASE OF MULTIPLE IDENTICAL FORMS AFTER MANIPULATING
//var id = element.attr("id");
var option = $("#name").val(); //obtaining the selected value
var dataString = 'name='+ option; //preparing the datastring to send to get.php
$.ajax({ //using ajax
type: "POST", //request type post, you can use get here
url: "get.php", //page you're sending request
data: dataString, //datastring you are passing
dataType:'html', //responsetype you are wanting
cache: false,
success: function(data){ //in case of successful response from get.php, response is in dataType format inside variable "data"
$("#output").append(data); //doing stuff on this page from response received from get.php
}
});
return false;
});
});
</script>
<form>
<select id="name">
<option >---</option>
<option value="1">ONE</option>
<option value="2">TWO</option>
<option value="3">THREE</option>
</select>
</form>
<div id="output">THINGS WILL COME HERE, DELETE THIS TEXT IN ACTUAL USE<br/></div>
</body>
</html>
get.php
<?php
if(isset($_POST['name'])){
switch($_POST['name']){
case '1': echo "YOU HAVE SELECTED ONE<br/>";
break;
case '2': echo "\nYOU HAVE SELECTED TWO<br/>";
break;
case '3': echo "\nYOU HAVE SELECTED THREE<br/>";
break;
default : break;
}
}
?>
关于php - 你如何从表单元素<select>和<option>中获取数据到表单提交的php中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16412321/