1

我正在使用 PHP 创建一个 JavaScript 文档。它确实做了两件事:

  1. 读取一个包含一些我用作模板的 HTML 文件的目录,然后输出一个对象,其中包含表示文件名的键:值对:内容,最终将类似于以下内容:

    var HTML = {
        "blogpost.html": '<div>{post}</div>',
        "comment.html" : '<div class="comment">{comment}</div>'
    };
    

    这允许我用来HTML["template.html"]附加从 AJAX 请求接收到的模板化数据。

  2. 读取包含 JavaScript 文件的目录并将其内容直接输出到文档中。

在本地它工作正常,但是当我上传后尝试时出现此错误:

Uncaught SyntaxError: Unexpected token ILLEGAL

我尝试将我从每个 HTML 和 JS 文件中获得的输出包装成如下内容:

preg_replace('/\s{2,}/', '', $output);
addslashes($output);
mysql_real_escape_string($output);

以及这些的组合,但仍然是相同的错误。

如何可靠地输出我试图放置在输出中的 HTML 和 JavaScript?

这是我正在使用的当前整个 PHP 脚本(它在本地工作,但奇怪的是不能在线工作):

header("Content-type: application/x-javascript");


// Write HTML templates.
$dir = dir($_SERVER['DOCUMENT_ROOT'] . '/view/html/');
$files = array();

while($file = $dir->read())
{
    if(strpos($file, ".html"))
    {
        $key = substr($file, 0, strpos($file, ".html"));
        array_push($files, '"' . $key . '": \'' . compress(file_get_contents($dir->path . $file)) . "'");
    }
}

echo 'var HTML = {' . implode(",", $files) . '};';




// Output other JavaScript files.
$js = array();

array_push($js, file_get_contents("plugin/jquery.js"));
array_push($js, file_get_contents("plugin/imagesloaded.js"));
array_push($js, file_get_contents("plugin/masonry.js"));
array_push($js, file_get_contents("base/master.js"));
array_push($js, file_get_contents("plugin/ga.js"));

echo implode("", $js);


// Compress a JavaScript file.
function compress($str)
{
    return addslashes(preg_replace('/\s{2,}/', '', $str));
}
4

4 回答 4

2

您可以json_encode()用于任何 PHP -> JS 转换:

while ($file = $dir->read()) {
    if(strpos($file, ".html")) {
        $key = substr($file, 0, strpos($file, ".html"));
        $files[$key] = compress(file_get_contents($dir->path . $file));
    }
}

echo 'var HTML = ' . json_encode($files) .';';
于 2012-09-25T06:25:32.323 回答
1

这是一个解析器错误,所以问题发生在你的代码甚至运行之前。

我建议检查您正在使用的两个运行时的 PHP 版本。使用您计划部署到的相同运行时进行开发和测试将是理想的。

于 2012-09-25T06:22:49.910 回答
0

这也发生在我之前。

我假设您复制了您在 Github 之类的网站上发布的部分代码,或者您的编辑器已经塞满了。

众所周知,隐形字符潜伏在此类文件中。

解决此错误的方法是在记事本 (Windows) 或 TextEdit (Mac) 等纯文本编辑器中键入包含错误的代码行、其上方的行和下方的行。输入后,使用Ctrl-ACmd-A(全选),然后复制它并在您的普通代码编辑器中替换代码。

应该修复错误。

于 2012-09-25T06:47:54.657 回答
0

我已经想出了如何在我目前的情况下解决这个问题。

背景:

我的本地机器正在运行 PHP 版本5.3.5
我的主机正在运行 PHP 版本5.2.17

问题出现在每个加载的 HTML 文档的末尾,文档的最后一行没有空格或制表符,例如

<div>
    content
</div> <-- at the beginning of this line

解决方案:

我更改了preg_replace()与每个文件的输出一起使用的语句,以便它也可以匹配换行符,这似乎已经修复了它。

return preg_replace('/\s{2,}/', '', $str); // Old
return preg_replace('/\s{2,}|\n/', '', $str); // New
于 2012-09-25T06:58:11.940 回答