[英]Converting Javascript to PHP Variable
我正在尋找一些幫助我試圖獲得在第一個下拉列表中選擇的值 (id="select1") 在經過一些研究后不提交表單我已經能夠獲得第一個下拉列表的值和 output帶有以下警報。
<select name="select1" id="select1" class="form-control" required="required"
onchange="getValue(this)">
<script>
function getValue(obj){
alert(obj.value);
}
</script>
我正在努力做的是將它存儲為 php 變量,我可以在第二個下拉列表中使用它(id="select2),這是我的代碼,任何幫助我指向正確方向的幫助將不勝感激。
<div class="form-group">
<label>Select 1</label>
<br>
<select name="select1" id="select1" class="form-control" required="required"
onchange="getValue(this)">
<option disabled selected>-- Select 1 --</option>
<?php
$records = mysqli_query($conn, "SELECT name1 From table_001");
while($row = mysqli_fetch_array($records))
{
echo "<option value='". $row['name1'] ."'>" .$row['name1'] ."</option>";
}
?>
</select>
</div>
<script>
function getValue(obj){
return(obj.value) ;
}
</script>
<?php
$phpvar = "OUTPUT OF THE ABOVE JS";
?>
<div class="form-group">
<label>Select 2</label>
<br>
<select name="select2" id="select2" class="form-control" required="required">
<option disabled selected>-- Select 2 --</option>
<?php
$records1 = mysqli_query($conn, "SELECT name2 From table_002 where name1 = '$phpvar'");
while($row = mysqli_fetch_array($records1))
{
echo "<option value='". $row['name2'] ."'>" .$row['name2'] ."</option>";
}
?>
</select>
</div>
如果我正確理解了您的問題,您不能只在 php 中“存儲”一個變量。 PHP是服務器端,JS是客戶端。 在它們之間交換數據的唯一方法是 http 請求-響應對。 (我們不是在談論 websockets 等)
我不認為這是你的情況,因為你首先需要提交第一個表單,然后頁面將被刷新,新頁面將在第一個表單被清除但從 php 插入所需的值后返回形式
這是您的首選解決方案。 您可以使用XMLHttpRequest (舊方式)或fetch (現代方式)發出 ajax 請求。 這是瀏覽器中的兩種原生方式(也存在很多庫,例如 jquery.ajax(),它們大多是上述這兩種方法之上的包裝器)。
這是使用 fetch API 的基本示例,您可以將其放在第一個 select 的 onChange 事件處理程序中(:
fetch('./some_address.php')
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// your server-side script may return a complex (or not :) json object or just a plain text, read the documentation for your case
return response.json(); // or return response.text();
})
.then((data) => {
// do whatever you need with your response from the server, for example set the value for your second select
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.