我可以将所需文件的全部内容存储在JavaScript变量中吗


Can I store the whole content of a required file in a JavaScript variable?

这似乎是一个奇怪的问题。也许这也是错误的做法。但我必须这样做:

  • 一页上有几个菜单项
  • 每个页面的内容都存储在一些.phtml文件中
  • 页面加载时显示默认内容(使用require
  • 所有其他内容也应该加载,并且应该存储在JavaScript数组中
  • 当用户单击链接时,内容将被交换

问题是:

  • 不应使用AJAX
  • 所有内容都不能在一开始就添加,对于好的旧SEO

所有部分都很简单,除了:如何将内容放入JavaScript数组。像content.push('<?php print require 'page.phtml'; ?>');这样的东西当然不起作用,因为它将返回一个多行字符串,这在JavaScript中是不起作用的。欢迎所有想法。也许我忽略了一些非常简单的事情。

<script>
<?php
ob_start();
require 'page.phtml';
$contents = ob_get_clean();
echo "var content = ".json_encode($contents);
?>
</script>

如果你的page.phtml文件中没有php代码,你可以让变得更容易

<script>
<?php
echo "var content = ".json_encode(file_get_contents('page.phtml'));
?>
</script>

很明显,你也可以这样使用它:

echo "content.push(".json_encode($contents).");";

为什么不启用

<?php
function json_require($filepath) {
  ob_start();
  require($filepath);
  return json_encode(ob_get_clean());
}
?>
...
content.push(<?=json_require('page_1.phtml');?>);
content.push(<?=json_require('page_2.phtml');?>);
content.push(<?=json_require('page_3.phtml');?>);
content.push(<?=json_require('page_4.phtml');?>);

您可以使用隐藏的div,而不是使用js数组,在页面的末尾,这样它们就不会影响seo。然后使用这些div id来交换您的内容。

我希望您使用的是jQuery,如果没有的话,即使使用简单的js也可以做到这一点。

让我详细说明

<script>
function shouldBeCalledAtSomeEvent(page_id)
{
   var html = $('#'+page_id+').html();
   $('#idOfYourTargetElem').html(html)
}
</script>
<!-- end of your main file -->
<div style="display:none" id="page_1">
include('page_1.phtml');
</div>
<div style="display:none" id="page_2">
include('page_2.phtml');
</div>
<div style="display:none" id="page_3">
include('page_3.phtml');
</div>

如果你不能使用ajax,并且担心seo,我建议你使用@rupesh answer的修改版本:将html存储在脚本标记中,这样js就可以访问它们,而不会被爬网程序读取:

<script type="text/hidden-menu" class="hidden_menu" >
    include('page_1.phtml');
</script>
<script type="text/hidden-menu" class="hidden_menu" >
    include('page_2.phtml');
</script>
<script type="text/hidden-menu" class="hidden_menu" >
    include('page_3.phtml');
</script>

然后你可以很容易地在js:中构建你的数组

var content = [],
    contentNodes = document.getElementsByClassName('hidden_menu'),
    i=0;
for(;i<contentNodes.length;i++)
   content.push(contentNodes[i].innerHTML);    

瞧:您有一个内容数组,它保存从php发送的html,而不使用ajax,也不影响seo。