我有以下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
}
如果不使用表单,就无法使用$_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>
如果没有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