我不知道我问的是否正确,但我会尝试:
例如,我有 5 个按钮,每个按钮都有不同的类。
<button class="table1">Table1</button>
<button class="table2">Table2</button>
// etc... //
我有脚本,如果单击按钮,它会启动 ajax 调用:
$(".table1").click(function(){
$.ajax({url:"test.php",success:function(result){
$(".result").html(result);
}});
});
我有php脚本,它应该通过单击按钮类选择表(这是我的问题):
foreach($db->query('SELECT * FROM table1') as $row) {
echo '<div><b>'.$row['info1'].'</b></div>';
echo '<span>'.$row['info2'].'</span><br/>';
echo '<span>'.$row['info3'].'</span>';
echo '<br/><br/><br/>';
}
问题:这所有脚本都在工作,但是,不知何故我需要做,如果我单击table1,那么php查询应该选择table1,如果单击table2,则查询应该选择table2 ...等。
我不擅长阿贾克斯。我只知道php基础知识。
对不起,英语不好。
拆分你的CSS类,例如
<button class="clickable" data-tableid="1">...</button>
<button class="clickable" data-tableid="2">...</button>
,然后仅将单击句柄附加到 .clickable
类。单击事件将包括单击了哪个元素,您可以从中提取该特定按钮的数据属性:
$('.clickable').click(function(e) { // 'e' is the click event
sourceElement = e.target; // get the button which was clicked
tableid = sourceElement.dataset.tableid; // extract its tableid data attribute
... ajax call here ...
});
我建议修改HTML:
<button id="table1" class="table">Table1</button>
<button id="table2" class="table">Table2</button>
和JavaScript代码:
$(".table").click(function(e){
$.ajax({url:"test.php?table=" + $(e.target).attr('id'),success:function(result){
$(".result").html(result);
}});
});
然后,您可以从 $_GET['table'] 变量中检查 PHP 中单击的表。
只需复制,粘贴运行此代码
在索引中.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button id="table1" class="table">Table1</button>
<button id="table2" class="table">Table2</button>
<button id="table3" class="table">Table3</button>
<script>
$( ".table" ).click(function() {
var table = $(this).attr('id');
$.ajax({//create an ajax request to load_page.php
type: "POST",
url: "sample.php",
data:{"data":table},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
});
</script>
</body>
</html>
在样本中.php
<?php
if(isset($_POST['data'])){
$table = $_POST['data'];
foreach($db->query("SELECT * FROM '$table'") as $row) {
echo $db->query("SELECT * FROM '$table'");
echo '<div><b>'.$row['info1'].'</b></div>';
echo '<span>'.$row['info2'].'</span><br/>';
echo '<span>'.$row['info3'].'</span>';
echo '<br/><br/><br/>';
}
}
?>