這是 HTML 中的選擇和選項。我在這里使用 jquery。我需要獲取兩個 select 的值并將值傳遞給 ajax.php,我需要在其中使用這兩個值來檢查我的資料庫并繼續進行另一個相關的下拉串列。
<label>Select Number: </label>
<select id= "number" onchange="FetchState(this.value)" required>
<option value="0">-- 0 --</option>
<option value="1">-- 1 --</option>
<option value="2">-- 2 --</option>
<option value="3">-- 3 --</option>
</select>
<label>Select letter: </label>
<select id="alphabet" required>
<option value="a">-- a --</option>
<option value="b">-- b --</option>
<option value="c">-- c --</option>
<option value="d">-- d --</option>
</select>
<select id="dependent">
</select>
這是我下面寫的腳本代碼。
function FetchState(id) {
$("#dependent").html('');
$.ajax({
type: "POST",
url: "ajax.php",
data: {
number: id,
},
success: function(data) {
$("#dependent").html(data);
}
});
}
</script>
我需要通過 jquery(ajax) 將兩個值傳遞給 PHP 才能繼續。這里字母和字母值都應該被獲取并作為jquery中的資料傳遞給ajax.php
uj5u.com熱心網友回復:
html 有點奇怪,但是因為您總是會在兩個下拉串列中進行選擇,所以我們可以簡單地做
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function FetchState() {
id = $('#number option:selected').val();
alp = $('#alphabet option:selected').val();
$.ajax({
type: "POST",
url: "ajax_endpoint.php",
data: {number: id, alphabet: alp},
success: function(data) {
$("#dependent").html(data);
}
});
}
</script>
</head>
<body>
<form method="POST" >
<label>Select Number: </label>
<select id= "number" onchange="FetchState()" required>
<option value="0">-- 0 --</option>
<option value="1">-- 1 --</option>
<option value="2">-- 2 --</option>
<option value="3">-- 3 --</option>
</select>
<label>Select letter: </label>
<select id="alphabet" onchange="FetchState()" required>
<option value="a">-- a --</option>
<option value="b">-- b --</option>
<option value="c">-- c --</option>
<option value="d">-- d --</option>
</select>
<select id="dependent"></select>
</form>
</body>
</html>
如果虛擬 ajax_endpoint.php 是這個
<?php
echo '<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>';
?>
它應該為您填寫第三個下拉串列
uj5u.com熱心網友回復:
宣告一個陣列,推送到它,然后在到達陣列中的兩個專案時觸發 ajax 呼叫怎么樣?
var bothnumbers = [];
function FetchState(id) {
bothnumbers.push(id);
console.log('your array: ' bothnumbers);
if(bothnumbers.length == 2){
console.log('fire function now that two are chosen');
$("#dependent").html('');
$.ajax({
type: "POST",
url: "ajax.php",
data: {
number: bothnumbers,
},
success: function(data) {
$("#dependent").html(data);
}
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/537484.html
下一篇:修改輸入欄位時錯誤所有產品都更新
