我有以下HTML摘录:
<div id="result" class = "hide">
<select id = "selectIngredients">
<option>Choose a recipe</option>
<option value="Carrot">Carrot</option>
<option value="Cabbage">Cabbage</option>
<option value="Broccoli">Broccoli</option>
</select>
<button class="btn" onClick="viewRecipe()"> View Recipe</button>
</div>
我试图使用一些PHP来获得单击按钮时选择的值。不用表格就可以吗?
当我执行以下操作时,它不起作用。
$selected_val = $_POST['selectIngredients']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
答案 0 :(得分:0)
如果不使用表单,则不能使用$ _POST;如果不想使用表单,则可以通过javascript检查以下代码来实现,它将为您提供帮助。
<script>
function viewRecipe(el)
{
var e = document.getElementById(el);
var strSel = e.options[e.selectedIndex].text;
alert(strSel);
}
</script>
<div id="result" class = "hide">
<select id = "selectIngredients">
<option>Choose a recipe</option>
<option value="Carrot">Carrot</option>
<option value="Cabbage">Cabbage</option>
<option value="Broccoli">Broccoli</option>
</select>
<button onClick="viewRecipe('selectIngredients');">Get Selected Item</button>
</div>
答案 1 :(得分:0)
如果没有html表单,则无法发送发布请求,但可以在 javascript / ajax。
这是$_POST
的示例:
function viewRecipe(){
var e = document.getElementById('selectIngredients');
var strSel = e.options[e.selectedIndex].text;
var req = new XMLHttpRequest();
req.open('POST', "pageName.php", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send('selectIngredients='+strSel);
req.onload = function() {
var res=req.response;
alert(res);
}
}
PHP代码:
if(isset($_POST['selectIngredients'])){
$selected_val = $_POST['selectIngredients'];
echo "You have selected :" .$selected_val;
}
如果您要将请求发送到同一页面,请参见$_GET
方法示例。
function viewRecipe(){
var e = document.getElementById('selectIngredients');
var strSel = e.options[e.selectedIndex].text;
window.location.href = window.location.pathname+"?selectIngredients="+strSel;
}
让我知道您是否遇到任何错误。 :D