解决此问题的一个好方法是使用AJAX 调用 PHP 脚本,该脚本将查询您的数据库,返回结果,然后将它们传递回 AJAX 回调。
您的 jQuery 将简单地侦听下拉列表中的 .change() 事件,然后调用 AJAX 脚本。
$('your_elem').change(function(){
// Get the values
var coin = $('your_elem option:selected').text();
var country = $('other_elem option:selected').text();
// Call the AJAX script
get_new_results(coin, country);
});
// AJAX script which will call the PHP
function get_new_results(coin, country) {
// Put the values in an array to pass to script
var json = { 'coin' : coin, 'country' : country };
// Create a request
$.ajax({
type: 'POST',
url : 'path/to/your/script.php',
data: { query : json },
cache: false,
// Update the table
success: function(data) {
// Remove all existing table data
$('your_table').remove();
// Your PHP file should echo back the new table, append this to the
// the old table container
$('table_container').append(data);
}
});
}
这应该为您提供一种更新表格的机制,现在我们将创建 PHP 文件,该文件将传回任何表格数据以更新您的表格。
<?php
// Variables
$coin = $_POST['query']['coin'];
$country = $_POST['query']['country'];
// Do some DB query
$query = 'SELECT * FROM table WHERE country = "' . $country . '" AND coin = "' . $coin . '"';
// Use PDO here to get your results
$res = PDO QUERY FETCH ALL;
// Loop through results;
$rows = "";
foreach($res as $object) {
$rows += '<tr><td>Specify your formatting</td></tr>';
}
// Echo out the new table to be appeneded, AJAX will capture this
echo '<table>' . $rows . '</table>';
好的,我没有对此进行测试,但我相当肯定它应该为您提供一个良好的入门基础,希望对您有所帮助:)
编辑:关于放置物品的说明
为了让 AJAX 工作,您需要在标题中包含对 jQuery 的引用,这是因为我们正在使用 jQuery 库来构建我们的 AJAX 调用,您可以在 http://jquery.com 下载 jQuery,或者您可以像这样使用外部托管的文件源:
<script src="http://code.jquery.com/jquery-latest.min.js">
您还需要阅读有关如何使用 PDO in order to reference the database 的信息,就您的应用程序结构而言,您可以使用以下内容:
- app
--- views
------ your_view.php
------ other_view.php
--- commands
------ update_table.php <---- this is the script AJAX calls
- public
--- css
----- your_style.css
----- other_style.css
--- js
----- jQuery.js <----- jQuery file, if you haven't sourced it externally
----- other_file.js
----- ajax_commands.js <----- the AJAX file containing all AJAX scripts
此结构实现了 MVC 框架,允许您为应用程序提供一些结构