使用AJAX如何根据数据库中可用的记录为下拉菜单生成选择?
如何在选择时使用这些选项从数据库预填充包含记录/行数据的表单?
这是我创造的我正在尝试做的模拟:
http://oi58.tinypic.com/2urb2ae.jpg
PHP FILE: contact_form.php
-----------------------------------------------------------
<?php
define('DB_NAME', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_HOST', 'xxx');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$connection){
die('Database connection failed: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($connection, DB_NAME);
if(!$db_selected){
die('Can\'t use ' .DB_NAME . ' : ' . mysqli_connect_error());
}
echo 'Connected successfully';
if (isset($_POST['itemname'])){
$itm = $_POST['itemname'];
}
else {
$itm = '';
}
if($_POST['mile']){
$mi = $_POST['mile'];
}else{
echo "Miles not received";
exit;
}
if($_POST['email']){
$email = $_POST['email'];
}else{
echo "email not received";
exit;
}
$sql = "INSERT INTO seguin_orders (itemname, mile, email)
VALUES ('$itm', '$mi', '$email')";
if (!mysqli_query($connection, $sql)){
die('Error: ' . mysqli_connect_error($connection));
}
CONACT FORM: formz.php
------------------------------------------------------------------------------
<html>
<header>
</header>
<body>
<form action="/demoform/contact_form.php" class="well" id="contactForm" method="post" name="sendMsg" novalidate="">
<big>LOAD PAST ORDERS:</big>
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<?php
$email = $_POST['email'];
$query="select * from tablename WHERE email={$_POST['email']}";
$res=mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($res))
{
?>
<option value="<?php echo $row['fieldname']; ?>"><?php echo $row['fieldname']; ?></option>
<?php
}
?>
</select>
</br>
<input type="text" required id="mile" name="mile" placeholder="Miles"/>
</br>
<input id="email" name="email" placeholder="Email" required="" type="text" value="demo@gmail.com" readonly="readonly"/>
</br>
<input id="name" name="itemname" placeholder="ITEM NAME 1" required="" type="text" />
</br>
<input type="reset" value="Reset" />
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
答案 0 :(得分:0)
使用例子,我们假设您要填写&#34;名称&#34;根据在&#34;性别&#34;中选择的选项进行选择选择:
<select name="gender" id="gender">
<option value="m">Male</select>
<option value="f">Female</select>
</select>
当没有选择任何内容时,&#34; name&#34; select为空:
<select name="name" id="name">
<option value="NULL">Please select a gender first</option>
</select>
所以,你要做的是:当性别选择得到一些选择时,你可以根据性别选择选项用值填充名称选择。
$(document).ready(function() {
$('select#gender').change(function(){
$('select#name').load('LOAD_NAMES_BASED_ON_GENDER.php?gender='+$(this).val());
});
});
负责根据性别加载名称的PHP文件应如下所示:
$gender = $_GET['gender'];
$list = // the way you retrieve your list of names from your DB
然后将这个$ list循环到一个选项列表中,例如:
foreach($list as $key=>$value)
echo '<option value="$key">$value</option>';
这很简单。 PS:load()函数是$ .ajax请求的别名,因为这里唯一的目的是检索数据。