javascript - PHP 'include'函数的现代JS方法

标签 javascript php html frameworks include

随着 JS 框架库的不断增长(自从我上次构建网站 ~ 2014 年以来),是否有一个简单的 JS 替代/替代 PHP 的“include”功能。或者 PHP include 仍然是包含代码块的相关方法吗?

我正在构建一个网站,想要实现一些基础功能,例如“包括”页脚、页眉、菜单等,但不想将所有页面都设为 .php - 这感觉有点笨拙且不必要。

我找到了相关帖子here引用了 Jekyll,但它更具体于 GitHub。任何正确方向的指针表示赞赏!

最佳答案

由于我的第一个答案没有涵盖感兴趣的问题,我决定完全编辑并替换答案。我们开始吧..

解决方案

1 - JQuery load() 函数

<!-- LOAD JQUERY -->
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>

<!-- "INCLUDE" external files with code -->
<script> 
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
</script>

2 - NPM gulp 包,可让您包含文件并传递一些参数/值

https://www.npmjs.com/package/gulp-file-include

<!DOCTYPE html>
<html>
  <body>
  @@include('./header.html')
  @@include('./main.html')
  </body>
</html>

gulp 任务的示例:

var fileinclude = require('gulp-file-include'),
    gulp = require('gulp');

    gulp.task('html', function() {
        return gulp.src(['./src/html/views/*.html'])
            .pipe(fileInclude({
                prefix: '@@',
                basepath: 'src/html'
            }))
            .pipe(gulp.dest('./build'));
    });

3 - 通过 document.write 函数纯 JavaScript 并通过 src 包含脚本

<script type="text/javascript" src="header.js"></script>

4 - 纯ajax请求,请求附加数据并将其放置在页面上应该放置的位置

5 - SSI(服务器端包含),正如我在评论中提到的

6 - iframe(尽管不是最好的方法)

7 - asp/jsp 服务器脚本包含(作为 php 服务器脚本包含的替代方案)

更多信息在这里:

Common Header / Footer with static HTML

Make header and footer files to be included in multiple html pages

希望您能从中找到最适合您需求的方法。

关于javascript - PHP 'include'函数的现代JS方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46408284/

相关文章:

javascript - 水平滚动时固定表格中的第一列

php - 如何将 Codeigniter 中的welcome.php 更改为类似index.php 的内容?

php - 如何使用 PHP 在 MySQL 中插入 now() 函数

php - PHP 5 中使用 mysql_query() 的调用是异步的吗?

jquery - 如果 jQuery 有焦点,如何防止切换操作

javascript - 如何使用 Ember js 在一个页面中显示多个路由?

javascript - 为什么我的函数调用应该由 setTimeout 调度立即执行?

类似于 C++ 中的 JavaScript 指针数组

javascript - 将州名添加到 d3.js 中的 map

HTML5/CSS - 扩展水平菜单