【问题标题】:Path issue with autoload function to get files for use in Ajax使用自动加载功能获取文件以在 Ajax 中使用的路径问题
【发布时间】:2012-11-06 08:57:39
【问题描述】:

所以我的项目使用了 MVC 框架,并且我有一个带有 Ajax 脚本的页面,我运行该脚本来从服务器获取内容。当在 Ajax 脚本中调用 PHP 脚本时,我想访问我的库中已有的类以在 PHP 脚本中使用。为此,我使用我所谓的 ajaxBootstrap 来调用适当的函数,然后实例化该特定 Ajax 脚本所需的对象。

要从我的库中加载这些类,我的 ajaxBootstrap 中有一个自动加载功能,因此我不需要使用一堆 require 和 include 语句。我的问题是由于自动加载功能的路径问题而没有加载这些文件。当我使用具有相同路径的 require 语句时,类加载没有问题,只有当我尝试使用自动加载功能加载它们时,才会收到 500 内部服务器错误。

这是我的 ajaxBootstrap 文件:

// This file routes Ajax requests made in JS files and instantiates a specific object to carry out the actions needed for that particular Ajax operation 

// Autoload any classes that are required
function autoLoad($classToLoad)
{
    if(file_exists('../library/' . $classToLoad . 'class.php')) // File in the library folder
    {
        require('../library/' . $classToLoad . '.class.php');
   }
    else if(file_exists('../../app/models/' . $classToLoad . 'class.php')) // File in the models folder
    {
        require('../../app/models/' . $classToLoad . '.class.php');
    }
}

spl_autoload_register('autoLoad');

// Determine which function to call based on the url that's listed in the Ajax request
switch($_GET['action'])
{
    case 'pageOne':
        pageOne();
        break;
    case 'pageTwo':
        pageTwo();
        break;
}

function pageOne()
{
    $test = new Test();
    $test->funcThatReturnStuff();
}

function pageTwo()
{
    $test2 = new Test2();
    $test2->funcThatReturnStuff();
}

就像我之前提到的,如果我使用 require 语句,例如:

require('../library/Test.class.php');
$test = new Test();
$test->funcThatReturnStuff();

类加载和工作得很好。但是在自动加载器函数中使用相同的路径会引发错误。真正奇怪的是,如果我在自动加载器中放置一个 else if 语句,该语句从我的 ajaxBootstrap 所在的文件夹中加载一个类,它也可以正常工作......

我知道我可以只使用 require 语句来解决问题,但我希望能够扩展项目并且以后不需要使用大量的 require 语句。顺便说一句,我使用 '../' 从我的 ajaxBootstrap 文件所在的位置获取到我的其他文件夹。

另外,为了补充我之前的帖子,我尝试使用define('ROOT', dirname(__FILE__) . '/')define('ROOT', $_SERVER['DOCUMENT_ROOT'] . '/path/to/folder/')../ 替换为绝对路径,这两种方法都不起作用,仍然给我Firebug 中的内部服务器错误。此外,我的错误日志中也没有收到任何错误。

【问题讨论】:

  • 您是否尝试过使用绝对路径(包括__DIR__dirname(__FILE__))? AFAIR 级联相对包含有一些问题。
  • @apfelbox 是的,我尝试将 ../ 替换为 define('ROOT', dirname(__FILE__) . '/'),甚至尝试使用 $_SERVER['DOCUMENT_ROOT'],但我仍然遇到同样的问题...
  • 我猜这与PHP bug posting有关。您能否将完整的错误消息添加到您的帖子中?
  • @apfelbox FireBug 中的错误是:NetworkError: 500 Internal Server Error - localhost/path/to/file
  • @apfelbox 我刚刚阅读了您提供的链接,我想知道相对路径错误是否在 file_exists() 内部搞砸了,因为就像我提到的那样,使用相同的 require 语句路径工作正常。

标签: php ajax path


【解决方案1】:

没关系...即使在过去几个小时盯着我的代码之后,我还是以某种方式错过了两个文件路径中缺少的句点。我有时讨厌编码...感谢所有花时间阅读本文的人。

【讨论】:

    猜你喜欢
    • 2022-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2017-10-01
    • 2021-07-15
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多