我需要使用 php 将 html 中的两个组合框连接到数据库,并使用组合框的结果从数据库中获取其他内容
例如
<div style="margin:5px">סוג הפעילות
<select name = "ex" id = "user" onchange="showUser(this.value)">
<option value = "0"> </option>
<?php while($row = mysqli_fetch_array($res)){ ?>
<option value = "<?php echo $row['NameEx'];?>"><?php echo $row['NameEx'];}?></option>
</select>
</div>
<div name = "sub" id="sub" style="margin:5px"> תת פעילות</div>
<div><button class="btn btn-primary" type = "submit" name="submit1" onclick = "calc()" >חשב</button></div>
我的 JavaScript 是:
function showUser(str){
if(str == ""){
}else{
var myDiv = document.getElementById("sub");
var arr = [];
var status = false;
$.ajax({ //sending to DB
url: 'subEx.php',
type: 'post',
data: { field:str},
success:function(response){
var parsed = JSON.parse(response);
for(var x in parsed){
arr.push(parsed[x]);
}
// console.log(arr[0]);
//Create and append select list
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
myDiv.appendChild(selectList);
//Create and append the options
for(var i = 0 ; i <= arr.length ; i ++){
console.log(arr[0].NameSub);
var option = document.createElement("option");
option.setAttribute("value", arr[i].NameSub);
option.text = arr[i].NameSub;
selectList.appendChild(option);
}
}
});
return true;
}
}
我将两个组合框与数据库连接起来,但是当我提交提交时,我无法访问第二个组合框的值。
如何获取该值并在提交时使用它?
最佳答案
你的第二个<select>
标签没有name
属性。因此,提交时不会发送任何内容。
selectList.setAttribute("name", "name_of_select");
那么,你应该有$_POST['name_of_select']
在服务器端可用。
此外,在您的 HTML 中,您应该有 <form>
标记以便能够提交您的值。
最后,你的while
循环似乎未闭合。
<form method="post" action="action.php">
<div style="margin:5px">סוג הפעילות
<select name="ex" id="user" onchange="showUser(this.value)">
<option value="0"> </option>
<?php while($row = mysqli_fetch_array($res)){ ?>
<option value="<?php echo $row['NameEx'];?>"><?php echo $row['NameEx'];?></option>
<?php } /*end while */ ?>
</select>
</div>
<div name="sub" id="sub" style="margin:5px"> תת פעילות</div>
<div><button class="btn btn-primary" type="submit" name="submit1" onclick="calc()" >חשב</button></div>
</form>
关于javascript - 使用 html 和 php 连接两个组合框和数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48971747/