我一直在尝试使用AJAX
和PHP
来创建动态更改的表单,在下拉框中选择索引会自动更改表单上显示的输入类型。我在onchange()
提交给AJAX
函数的表单上使用了一个选择框。该函数使用XML
来调用PHP
文件。我正在尝试切换的两种类型的输入是文件上传和下拉框,该下拉框由我在远程数据库上的数据填充。当我选择文件上传输入选项时,它显示正常,但是当我选择该选项时,PHP
数据库下拉框不会显示。
有谁能告诉我我做错了什么?
以下是我现在的代码:
文件名: test.php
<html>
<body>
<head>
<script>
function getInputs(str) {
var xmlhttp;
if (str == "") {
document.getElementById("display").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "grabtest.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<form action="">
<select id='RecipeSelect' onchange='getInputs(this.value)'>
<option selected value=''>Select</option>
<option value='N'>New file</option>
<option value='E'>Existing file</option>
</select>
<br>
<div id="display"></div>
<br>
</form>
</body>
</html>
文件名: grabtest.php
<?php
$q=$_POST["q"];
//connect to database on server
$con=mysqli_connect("connection","loginname","password","DBname");
//if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($q=""){
echo "";
}
elseif ($q="N"){
echo "Select file to upload: <input type='file' name='newfile'>";
}
elseif ($q="E"){
//creates a dropdown box where you can select desired field
$list = mysqli_query($con, "select * from TableName");
echo 'Recipes: <select name = "name">';
while ($row = mysqli_fetch_array($list))
{
echo '<option value = "' . $row["ID"] . '">' . $row["Recipes"] . '</option>';
}
echo '</select><br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
}
mysqli_close($con);
?>
答案 0 :(得分:0)
您正在查询字符串中使用q
并使用POST
。您需要在XHR的发送方法中使用GET
或发送q
。