gpt4 book ai didi

php - 在一个 PHP 脚本中输出多个 JavaScript 文件的可靠方法? (避免意外 token 非法)

转载 作者:行者123 更新时间:2023-11-30 13:14:29 25 4
gpt4 key购买 nike

我正在使用 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));
}

最佳答案

您可以使用 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) .';';

关于php - 在一个 PHP 脚本中输出多个 JavaScript 文件的可靠方法? (避免意外 token 非法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12577142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com