【发布时间】:2013-07-06 15:57:54
【问题描述】:
我在通读手册之前甚至在多次阅读手册之后都遇到了 glob 函数的问题,但我似乎仍然偶然发现了一些看似基本的问题。
过去我在返回图像时遇到问题,因为我使用的目录是绝对的,而不是相对的。我也遇到了从 foreach 返回图像的问题,因为我正在循环但没有将字符串添加到主字符串,因此只能获取最后一张图像等。
在经历过这些以前的问题后,我认为我已经克服了这些问题并且知道什么会起作用。我尝试使用的代码最终将位于通过 AJAX 加载的页面上的函数中。在加载的页面上调用该函数。
但是,我什至无法在静态页面上使用它!
我使用的代码是这样的:
<?php
$dir = '/portfolio/_images/design/curiousc/gallery/';
$files = glob(dirname(__FILE__).$dir.'*.{jpg,png,gif,jpeg}', GLOB_BRACE);
foreach ($files as $file){
$output = '<img class="project inner-module" src="'.$dir.basename($file).'" alt="'.$file.'" />';
$images .= $output;
};
var_dump($files); //Returns this: array(0) { }
//I know the $dir is correct as it loads the following code.
//For sake of reference, I have manually added the filename.
//$images .= '<img class="project inner-module" src="'.$dir.'1-portrait-900.png" alt="'.$file.'" />';
//I would eventually have this feature inside a function so would preferably have 'return' rather than 'echo'
echo $images;
?>
我已经尝试使用手动代码作为单行的$dir 并且可以正常工作,因此我知道该目录已正确列出。我还做了一个var_dump($files);,它在页面中返回“array(0) { }”。如果我错了,请纠正我,但这是否意味着它找不到任何文件?
任何帮助将不胜感激!该代码最终将列出与我的投资组合中特定项目相关的所有图像。
谢谢!
[编辑]
为了@Darhazer 的帮助,添加文件结构和 AJAX 脚本。
文件结构:
/_inc/js/ajaxtrigger.js *这是 AJAX 脚本所在和工作的地方。
/index.php 这是我测试 glob 函数的静态页面。
/portfolio/index.php 这是通过 AJAX 加载到 index.php 中的
/portfolio/project.php 这被加载到portfolio/index.php中,随后在/index.php中
/portfolio/_images/category/*project*/gallery/ 每个项目的图片目录
我知道 project.php 位于 /portfolio/ 中,但无论我将 src 设置为 /portfolio/_images/... 还是仅设置为 _images/...,我都无法使图像引用正常工作。
我用于 AJAX 加载的脚本是:
$(document).ready(function(){
bindNewClick();
function bindNewClick(){
$('a.ajaxtrigger').on('click', function(){
// The target for AJAX loading is set with data-target="target-name-here" applied to the <a>
// The target div needs to have an id that matches #target-target-name-here
var target = $('div#target-'+$(this).data('target'));
doAjax($(this).attr('href'), target);
return false;
});
}
function doAjax(url, container){
if(url.match('^http')){
var errormsg = 'Ah! AJAX can\'t load external content';
container.html(errormsg);
}
else {
$.ajax({
url: url,
timeout:5000,
success: function(data){
container.html(data);
bindNewClick();
},
error: function(req,error){
if(error === 'error'){
error = req.statusText;
};
var errormsg = 'Uh oh! There was an error: '+error;
container.html(errormsg);
},
beforeSend: function(data){
container.html('<p>Loading...</p>');
}
});
};
};
});
【问题讨论】:
-
并且目录
/portfolio/真的存在于服务器根目录中吗?因为那是您的绝对路径指定的内容。 (它们与您的网站 document_root 无关。) -
是的,使用手动编写的 img src 测试该目录确实存在。我已经修改了 glob 以包含 dirname(FILE) 。
-
HTML
<img>使用 web-relative 路径。 PHP 文件函数使用服务器绝对路径。现在已经给你解释了两次了。困难在哪里?您真的没有查看给定的帮助链接吗? -
好吧,没看懂,我是按照@Darhazer 的指示,提到了
dirname(__FILE__)。当我通过链接找到其他人的问题时,我不知道哪些部分是相关的,因为尝试将我的问题的答案与其他人的问题的答案相匹配并不总是那么容易。放下你的讽刺和简单的解释真的有那么难吗,“你需要使用$_SERVER["DOCUMENT_ROOT"],哦顺便看看这个链接。”无论如何,谢谢,我到了。