【发布时间】:2011-08-21 15:19:57
【问题描述】:
我所拥有的是一个 PHP 代码,它从 mysql 数据库生成一个 html 表,然后我尝试使用一个 jQuery 插件来使表可排序。我已经多次遇到这个问题,似乎无法在任何地方找到解决方案......为什么 jQuery(或者它是 Javascript 时期?)不能在 PHP 输出上工作?没有办法解决这个问题吗?
代码如下:
<html><head>
<title>MySQL Table Viewer</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://tablesorter.com/jquery.tablesorter.min.js"></script>
<script src="http://tablesorter.com/addons/pager/jquery.tablesorter.pager.js"></script>
<script>
$(document).ready(function()
{
$("#mytable").tablesorter();
}
);
</script>
</head><body>
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'lptm42b';
$database = 'sphinx';
$table = 'spheres';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table id=\"mytable\" border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?></table>
</body>
</html>
输出是:
<html><head>
<script src="../js/jquery_plugin.tablesorter.min.js"></script>
<script src="../js/jquery-1.6.min.js"></script>
<script src="../js/jquery_plugin.tablesorter.pager.js"></script>
<title>MySQL Table Viewer</title></head><body>
<h1>Table: lobby</h1><table id="mytable" border='1'><thead><tr><td>tableid</td> <td>name</td><td>datecreated</td><td>active</td></tr></thead>
<tbody><tr><td>12341231241</td><td>Oyunum1</td><td>2011-05-09 14:26:51</td><td>0</td> </tr>
<tr><td>6677768</td><td>m2</td><td>2011-05-05 14:26:39</td><td>1</td></tr>
<tr><td>ddf1</td><td>m3</td><td>2011-05-09 14:27:19</td><td>0</td></tr>
<tr><td>7856844444</td><td>m4</td><td>2011-05-09 14:27:31</td><td>0</td></tr>
<tr><td>xxxxde4rfd</td><td>m5</td><td>2011-05-09 14:27:43</td><td>0</td></tr>
</tbody></table>
</body></html>
<script>
$(document).ready(function()
{
$("#mytable").tablesorter();
}
);
</script>
更新:由于某种原因,chrome 视图源中的 end / script> 标记丢失了语法着色
【问题讨论】:
-
会报错吗?你用的是什么浏览器?
-
不要
echoHTML。并且:echo "<table id="mytable" border='1'><tr>";应该抛出一个语法错误。可以看到代码高亮显示存在引用问题。 -
您忘记关闭您的
<table>。 -
还是错了。你正在做的是回显字符串
"<table id="然后有一些未定义的常量mytable和另一个字符串" border='1'><tr>"。 -
您的脚本标签不在
<html></html>标签内。把它放在head里面。
标签: php jquery mysql html-table