如何使用 jQuery 保存此 PHP 下拉列表的值?



我在PHP中有这个下拉菜单,我想在jQuery中获取选定的值:

<p>
Choose device type :
<?php
echo "<select id='type_id_selected' name='device_type_id'>";
echo "<option value='Select'>Select</option>";
foreach ($dev_type_results as $row) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>"; ?>
</p>

我尝试使用此jQuery代码,但没有工作:

<script>
$('#type_id_selected').change(function() {
var data = "";
$.ajax({
type: "POST",
data: "value=" + $(this).val(),
async: false,
success: function(response) {
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
var select = $('equipe1');
select.empty();
$.each(array, function(index, value) {
select.append(
$('<option></option>').val(value).html(value)
);
});
});
</script>

编辑:我更改了jquery代码,现在我能够在jQuery中获取数据,但是,我不知道如何以某种方式保存可以在PHP代码中访问的值

<script type="text/javascript">
$(document).ready(function() {
$("select.device_type_id").change(function() {
var selectedType = $(this).children("option:selected").val();
//  access selectedType in PHP
});
});
</script>

您可以在JS中获取值,并向PHP文件发送AJAX POST请求。 .HTML

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Testing</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('select.unit').change(function() {
let selectedUnit = $(this).children("option:selected").val();
console.log(selectedUnit)
$.ajax({
url: "./data.php",
method: "POST",
data: {
unit: selectedUnit
},
dataType: "text",
success: function(html) {
$('#confirmation').html(html);
}
});
});
});
</script>
</head>
<body>
<select id="choose-first-unit" class="span-four unit">
<option value="m3">cubic meters</option>
<option value="cm3">cubic centimeters/milliliters</option>
<option value="dm3">cubic decimeters/litres</option>
<option value="hl">hectolitres</option>
<option value="cl">centilitres</option>
</select>
<div id="confirmation"></div>
</body>
</html>

PHP代码:对于第一个PHP文件

<?php
session_start();
$unit = $_POST['unit'];
$_SESSION['unit'] = $unit;
?>

在您要访问该值的另一个文件中

session_start();
$data = $_SESSION['unit'];

最新更新