我的目标是让用户将照片上传到根目录中名为“userupload”的目录。该文件夹将包含 .jpg 图像。
我现在想将从“userupload”目录到不同.php页面的所有图像路径调用到名为“content”的div中,如下所示: <p><img class=resizeme src="userupload/uploadimage1.jpg"></p>
我找到了这个脚本,我只能返回图像文件名..这很好,但我不知道如何编辑代码以将其放置在正确的路径中。
“这将列出您在 url: 下定义的文件夹中的所有 jpg 文件,并将它们作为段落附加到 div 中。也可以使用 ul li 来完成此操作。”
$.ajax({
url: "useupload",
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('#content')
});
}
});
最佳答案
这是您可以使用的 PHP:
image_listing.php:
<?php
$imageLinks = array();
$dh = opendir("userupload");
while ( $file = readdir($dh) )
{
$tempArray = explode(".",$file);
if ( isset( $tempArray[1] ) && $tempArray[1] == "jpg" )
{
array_push( $imageLinks, 'http://example.com/userupload/' . $file );
}
}
closedir($dh);
echo json_encode( $imageLinks );
这将返回一个链接数组,然后您可以在 JavaScript 中使用它:
$.get('image_listing.php', function (array) {
$.each(array, function(){
$('#content').append('<p><img class="resizeme" src="' + this + '"></p>');
});
});
这是一个有效的快速示例,但您可能应该构建一个 HTML 片段(而不是每次在循环中都点击 DOM):
$.get('image_listing.php', function (array) {
var container = $('<div'>);
$.each(array, function(){
container.append('<p><img class="resizeme" src="' + this + '"></p>');
});
$('#content').append( container.html() );
});
关于php - 使用 Javascript/jquery 将 url 从单独的目录填充到 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13150762/