【发布时间】:2017-01-18 01:11:55
【问题描述】:
我是网页设计的新手。一起学习PHP和HTML。 我正在尝试根据 SQL 结果动态显示图标的数量。 我有一个 PHP 代码来查询数据库并获取结果。我有 HTML 代码,它只显示我指示的数量(静态)。我想我几乎接近实现它,但发现很难整合。我应该为此使用 AJAX 吗?我该怎么做?
index.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM table";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
test.html
<html>
<head>
<title>EXAMPLE</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript">
// AJAX uery.Call PHP and retrieve the result .Based on the number of rows, display the below elements
</script>
<div id="container">
<a href="#">
<figure>
<button title="User1" class=" fa fa-user" style="font-size:100px;color:**green**"></button>
<figcaption>User1</figcaption>
</figure>
</a>
<a href="#">
<figure>
<button title="User2" class="fa fa-user" style="font-size:100px;color:**red**"></button>
<figcaption>User2</figcaption>
</figure>
</a>
</div>
</body>
</html>
<style>
#container {
text-align: center;
}
a, figure {
display: inline-block;
}
figcaption {
margin: 10px 0 0 0;
font-variant: small-caps;
font-family: Arial;
font-weight: bold;
color: #bb3333;
}
figure {
padding: 5px;
}
img:hover {
transform: scale(1.1);
-ms-transform: scale(1.1);
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-o-transform: scale(1.1);
}
img {
transition: transform 0.2s;
-webkit-transition: -webkit-transform 0.2s;
-moz-transition: -moz-transform 0.2s;
-o-transition: -o-transform 0.2s;
}
</style>
如果状态为“是”,则图标应为绿色。如果否,红色。您能否帮我整合并实现这一目标。
【问题讨论】:
-
你可以直接使用
array_push($jsonArray, $row),因为$jsonArrayItem的键和$row是一样的。 -
处理 AJAX 响应的 Javascript 代码在哪里?
-
代码应该遍历返回的数组,将适当的项目附加到
#container。你可以根据status属性的值给它们分配不同的类,然后CSS会根据类分配颜色。 -
@Barmar :我尝试了一些 AJAX 的 sn-p 来调用 PHP 并获得结果。但这并没有成功。也许,你可以在这里帮助我。
-
您的脚本是您在问题中添加评论的位置吗?您不能在具有
src的同一<script>标记中拥有脚本,您需要另一个<script>code here</script>标记。
标签: javascript php html mysql ajax