At first, you will need a js event listener to trigger an ajax call, when the select box is changed:
// Attach event listeners when document is loaded (DOM tree is ready)
$(document).ready(function() {
// Trigger ajax call when select#pd is changed
// if you use jquery version lower than 1.7
// use $('#pd').live('change', function() {});
$('#pd').on('change', function() {
// The data to send though the ajax call
// if it's not the value of the select what you need
// to query your database, change it
var postData = {
'id': $(this).val(),
};
// test.php is the target of the ajax call
// if you have your php code in an other file,
// change it
$.post( 'test.php', postData, function(data, status) {
// $('#div_container') is where you want to display
// the result of your ajax call
$('#div_container').html(data);
});
});
});
在test.php文件中你需要查询数据库,在上面提到的div容器中创建你要显示的结果:
<?php
// Connect to the database, if needed
$host = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'database_name';
$mysqli = new mysqli($host, $user, $pass, $db);
// check connection
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Data provided by the ajax call
$id = $mysqli->escape_string( $_POST['id'] );
// Query your data from database
// Obviously, you have to write a query to aquire the desired data
$query = "select * from table where column = '$id';";
// Create the required html structure from query data to return
// In this case, I want to create a table
// containing 4 columns(Col0..Col3) of my result set
ob_start();
if( $result = $mysqli->query($query) ) {
?><table>
<thead>
<tr>
<th>Col0</th>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody><?php
while( $row = $result->fetch_assoc() ) {
?><tr>
<td><?php echo $row['Col0']; ?></td>
<td><?php echo $row['Col1']; ?></td>
<td><?php echo $row['Col2']; ?></td>
<td><?php echo $row['Col3']; ?></td>
</tr><?php
}
?></tbody>
</table><?php
// Free result set
$result->free();
}
else {
// Handle failed query
printf("Error: %s\n", $mysqli->error);
exit();
}
// Close connection if needed
$mysqli->close();
// Gather the data from ob
$html = ob_get_contents();
ob_end_clean();
// Return the html structure
echo $html;
如果您对此有任何疑问,请随时提出。