虽然这是关于stackoverflow的常见问题,但似乎在每个实例中,答案似乎都特定于属于提出问题的人的代码。在处理完我自己的代码之后,我觉得好像我只有一些流氓行远离这项工作。基本上,我想要做的是过滤已输出到动态表的php mysql查询的结果。我想通过创建一个选择类型下拉列表来执行此操作,该列表将根据不同的值(即按字母顺序或按ID)对初始php查询中的数据进行排序。我希望这一切都在客户端完成,而无需刷新页面。有关我正在谈论的内容的示例,请观察此页面右侧靠近标题下方的排序下拉菜单:http://www.walmart.com/browse/3944_3951_132982
有人可以看看我的代码,并指出我仍然出错,或至少指出我的质量教程的方向。谢谢!
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css"/>
<title>Rg Distribution</title>
<script>
function sortResult(str)
{
if (str=="")
{
document.getElementById("result").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("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","condiments.php?q"=+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="logo"><img id="mainlogo" src="rglogo.png">
<div id="header">
<div id="ulwrapleft">
<ul id="nav_left">
<li><a href="index.html">home</a></li>
<li><a href="products.html">our products</a></li>
</ul>
</div>
<div id="ulwrapright">
<ul id="nav_right">
<li>where to buy</li>
<li>contact</li>
</ul>
</div>
</div>
</div>
<div class="mainbody">
<form>
<select name="sortby" onchange="sortResult(this.value)">
<option value="ID" selected>ID</option>
<option value="product_name">name</option>
</select>
<button type"submit">submit</button>
</form>
<div id="result"><?php echo $dyn_table; ?></div>
</div>
</body>
</html>
PHP代码:
<?php
$username = "";
$password = "";
$hostname = "";
$db_name = "";
$conn = mysqli_connect($hostname, $username, $password, $db_name) or die("Unable to connect");
$sql = "SELECT * FROM food_products WHERE alt_tag1 = 'condiment' ORDER BY ID";
$result = mysqli_query($conn, $sql);
$i = 0;
$dyn_table = '<table border="0" cellpadding="10">';
while($row = mysqli_fetch_array($result)){
$id = $row["ID"];
$product_name = $row["product_name"];
$image = $row["image"];
$link = $row["link"];
if ($i % 3 == 0) {
$dyn_table .= '<tr><td><a href="' . $link . '">' . '<img src=' . $image . '>' . '</a>' . '<br>' . $product_name . '</td>';
} else {
$dyn_table .= '<td>' . '<img src=' . $image . '>' . '<br>' . $product_name . '</td>';
}
$i++;
}
$dyn_table .= '</tr></table>';
mysqli_close($conn);
?>