如何通过php创建var javascript?
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words = $bad_words."".$resilt_row [word].",";
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?PHP echo $bad_words; ?>"];
alert(bad_words);
</script>
我想得到像这样的{j}这个var bad_words = ["fuck", "ass"];
警报时,它只会得到空白结果。
我该怎么做?
答案 0 :(得分:1)
<?php
include("connect.php");
$query = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$badWords = [];
while($row = mysqli_fetch_array($query))
{
$badWords[] = $row['word'];
}
JS
<script>
var bad_words = <?= json_encode($badWords); ?>;
alert(bad_words[0]);
console.log(bad_words);
</script>
如果它是一个数组,我不喜欢粘合字符串然后将其作为具有json_encode()函数的数组传递。同样在视图中,使用<?= ?>
标记
答案 1 :(得分:0)
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = $resilt_row['word'];
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?php print implode('","',$bad_words); ?>"];
alert(bad_words);
</script>
答案 2 :(得分:0)
如果你想把它们警告为一个字符串,你可以这样做:
<script>
var bad_words = <?php echo json_encode($bad_words) ?>;
console.log(bad_words);
</script>
否则,您可以将它们打印为数组:
Easy Install. $ sudo apt-get install python-setuptools python-dev build-essential
pip. $ sudo easy_install pip
virtualenv. $ sudo pip install --upgrade virtualenv.
python3-dev tools.$sudo apt-get install python3-dev
答案 3 :(得分:0)
您正在制作的琴弦不是您想要的琴弦 你没有添加引号。
这样做,使用数组更好:
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$bad_words = array();
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = "'" . $resilt_row[word]. "'";
}
然后,在你的js中:
var bad_words = ["<?php echo implode(",", $bad_words) ?>"];
或(简称)
var bad_words = ["<?= implode(",", $bad_words) ?>"];