我想通过 jQuery 回显 HTML 下拉值:
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<script>
function displayVals() {
var singleValues = $( "#single" ).val();
$( "p" ).html( "<b>Single:</b> " + singleValues);
}
$( "select" ).change( displayVals );
displayVals();
</script>
并在 PHP 中回显下拉值:
<?php
echo $single;
?>
最佳答案
如果不先提交表单,则无法在 PHP 中访问选择值。
这是一个提交到名为 submit.php 的文件的示例表单
<form method="post" action="submit.php">
<select id="my_select" name="my_select">
<option value="1">One</select>
<option value="2">Two</select>
<option value="3">Three</select>
</select>
</form>
submit.php 的内容看起来像这样......
<?php
echo $_POST['my_select']; // Will output the value of my_select when the form was submitted
?>
您还可以使用 ajax 将数据从您的表单提交到 PHP 页面,让 PHP 页面生成一些 HTML 输出并将其返回给您的 jQuery,从那里您可以将生成的 HTML 插入到一个元素 (div) 中你的页面。
<form id="my_form" method="post" action="submit.php">
<label>Select the number of items you'd like @ £5.00 each</label><br>
<select name="my_select">
<option value="1">One</select>
<option value="2">Two</select>
<option value="3">Three</select>
</select>
</form>
<div id="result"></div>
创建一个 PHP 页面以接收来自表单的数据。
$price = 5.00;
$noOfItems = $_POST['my_select'];
$totalCost = $price * $noOfItems;
echo "<p>$noOfItems @ $price will cost you $totalCost";
然后使用一些 jQuery 将表单中的数据提交到后台的 PHP,然后将生成的 HTML 放入#result div。
<script type="text/javascript">
$(document.ready(function(){
$("#my_select").change(function(){
$.post("submit.php", $("#my_form").serialize(), function(response){
$("#result").html(response);
});
});
}))
</script>
关于javascript - 从 jQuery 回到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33653425/