-1
<script type="text/javascript">
var category = new Array("category1", "category2");
</script>

我的问题是,我有这个 PHP 查询:

<?php $query = mysql_query("SELECT category FROM table ORDER BY category DESC") or die(mysql_error());
while($sql = mysql_fetch_assoc($query))
{
echo $sql['category'];
}
?>

如何添加 $sql['category'] 作为 javascript "category" 的参数?

4

3 回答 3

2
<?php $query = mysql_query("SELECT category FROM table ORDER BY category DESC") or die(mysql_error());

$categories=array();
while($sql = mysql_fetch_assoc($query))
{
$categories[]= $sql['category'];
}

echo json_encode($categories);
?>
于 2013-08-05T14:38:42.840 回答
0

如果只是一个:

<script type="text/javascript">
var category = new Array("category1", "category2", "<?php echo $category; ?>");
</script>

其他(尽管它也适用于一个):

<?php $query = mysql_query("SELECT category FROM table ORDER BY category DESC") or die(mysql_error());
$categories = array();
while($sql = mysql_fetch_assoc($query))
{
    $categories[] = $sql['category'];
}
?>
<script type="text/javascript">
    var categories = new Array("<?php echo implode('","',$categories); ?>");
</script>
于 2013-08-05T14:39:03.337 回答
0

有很多方法可以做到这一点。一个例子可以是:

<script type="text/javascript">
    var category = new Array(
        <?php
            while($sql = mysql_fetch_assoc($query))
            {
                echo "'{$sql['category']}'";
            }
        ?>
    );
</script>
于 2013-08-05T14:42:00.420 回答