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

标签 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

最佳答案

一个简单的好方法是使用 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/

相关文章:

javascript - 使用函数生成器将值返回到 GraphQL Mutation 中的输出字段

php - 如何以原子方式重新排序 MongoDB 中的数组项?

php - 使用 PHP 上传到存储桶内的 AWS S3 'folder'

jquery - 如何使用 Pace.JS 获取进度百分比

javascript - Jquery unbind() 不适用于联系表单

javascript - 如何在最初由ajax加载时将表单作为GET方法提交

JavaScript,没有 JQuery 请问,如何获取 iframe 中特定标签的总数

javascript - Ascensor.js IE8

php - 在 php 中搜索多个值

javascript - 在 jquery 中追加行时重复