PHPを使用してJavaScriptドキュメントを作成しています。それは2つのことをします:
テンプレートとして使用するいくつかの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));
}