我正在使用 PHP 创建一个 JavaScript 文档。它确实做了两件事:
读取一个包含一些我用作模板的 HTML 文件的目录,然后输出一个对象,其中包含表示文件名的键:值对:内容,最终将类似于以下内容:
var HTML = { "blogpost.html": '<div>{post}</div>', "comment.html" : '<div class="comment">{comment}</div>' };
这允许我用来
HTML["template.html"]
附加从 AJAX 请求接收到的模板化数据。读取包含 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));
}