在mysql表中获取图像以在javascript幻灯片中显示

时间:2016-03-09 15:01:17

标签: javascript php jquery html mysql

我在表images中有一些图片,字段为idnamephoto。图像存在于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>   

Screenshot of source code, when code is commented out

1 个答案:

答案 0 :(得分:1)

简单易用的方法是使用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函数。

我希望我能提供帮助。