我试着给它编码。 我还是被困在这上面。 主要目标是如果用户从mysqli数据库中选择值,选择它并将值发送到其他页面。 我知道人们推荐使用Ajax。 我试着用它。 还是不起作用。 我会把详细代码放在下面。
主页代码(Main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<a href="database1.php">click </a>
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
作为警告框,我正在获得它的值,但第二页得到错误,键值不存在。 这里是第二个页面(database1.php)-
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
那么出现了什么问题呢?
更新的答案
感谢她提到的@swati,使用form标记而不是AJAX(我知道它的简单答案),顺便说一句,谢谢你的回答。 :)
更新代码完整-
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
第二页(database1.php)变化不大-
$database=$_GET['tables'];
您在页面加载时调用的每个循环
将为您提供已经选择的值,而不是用户选择的值。此外,不需要此循环,因为您只需传递一个值。
您的脚本
应如下所示:
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
另外,由于您正在使用ajax,因此不需要为href=“database1.php”
提供a
标记,因为您正在使用ajax调用此页面。例如:您的a
标记应如下所示:
<a>click</a>
在php端的echo
将作为响应返回给ajax.因此,您的alert
内部成功函数将显示该值。