我在表 images
中有一些图像,字段是 id
、name
和 photo
。图片存在于 photo
中的位置。
此时,下面的代码没有得到任何图像,尽管应该有大约 4 张图像与查询匹配。满足查询的图像应进入 slideshowimages("")
变量。
<?php
// Connect to the database
require('mysqli.php');
// Query for a list of all existing files
$sql = "SELECT * FROM images WHERE name= '$pagetitle'";
$result = $conn->query($sql);
$directory = '';
while( $image = $result->fetch_assoc() )
$directory .= ($directory != '' ? "," : '') . ('"/images/'.$image["photo"] . '"');
// Check if it was successfull
if($image) {
// if there are images for this page, run the javascript
?><script>
//configure the paths of the images, plus corresponding target links
//NEED TO GET ALL RELEVANT IMAGE LOCATIONS INTO LINE BELOW
slideshowimages("<?php echo $directory ?>")
//configure the speed of the slideshow, in miliseconds
var slideshowspeed=2000
var whichlink=0
var whichimage=0
function slideit(){
if (!document.images)
return
document.images.slide.src=slideimages[whichimage].src
whichlink=whichimage
if (whichimage<slideimages.length-1)
whichimage++
else
whichimage=0
setTimeout("slideit()",slideshowspeed)
}
slideit()
</script> <?php
} else {
// If there are not any images for this page, leave the space blank
echo "";
}
// Close the mysql connection
$conn->close();
?>
head
中的 JavaScript
<script language="JavaScript1.1">
var slideimages=new Array()
var slidelinks=new Array()
function slideshowimages(){
for (i=0;i<slideshowimages.arguments.length;i++){
slideimages[i]=new Image()
slideimages[i].src=slideshowimages.arguments[i]
}
}
</script>
最佳答案
一个简单的好方法是使用 AJAX打电话,在 JSON 中获取您的图片网址数组,您可以将其解析为 javascript 数组,并进行迭代等。在这种情况下,额外的好处是您可以按语言将代码分隔到不同的文件中,这样可以生成更好的代码。
但是在您当前的代码中,您必须使用一个简单的循环来迭代您的 mysqli 结果。例如:
//...
// Query for a list of all existing files
$sql = "SELECT * FROM images WHERE name= '$pagetitle'";
$result = $conn->query($sql);
$directory = '';
while( $image = $result->fetch_assoc() )
$directory .= ($directory != '' ? ',' : '') . ("'/images/".$image['photo'] . "'");
//...
在这种情况下,您的 $directory
变量应该是这样的:
'/images/image1.jpg','/images/image2.jpg','/images/image3.jpg'
您希望可以将它作为参数列表传递给 javascript 函数。
希望能帮到你。
关于javascript - 获取 mysql 表中的图像以显示在 javascript 幻灯片中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35895141/