duanpanzhu2910 2017-09-25 14:56
浏览 62
已采纳

PHP'包含'函数的现代JS方法

With the ever-growing library of JS frameworks (since I last build a website ~ 2014) is there a simple JS replacement/alternative for PHP's 'include' function. Or is PHP include still a relevant method of including chunks of code?

I'm building a website and want to achieve some basics like 'including' footers, headers, menu's etc. but would rather not make all my pages .php - it feels a bit clunky and unnecessary.

I found a related post here referencing Jekyll but it was a bit more specific to GitHub. Any pointers in the right direction appreciated!

  • 写回答

1条回答 默认 最新

  • douzhouhan4618 2017-09-25 16:02
    关注

    Since my first answer wasn't covering the interested question I decided to fully edit and replace the answer. Here we go..

    Solutions

    1 - JQuery load() function

    <!-- 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 package which lets you includes file and pass some parameters/values

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

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

    an example of a gulp task:

    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 - pure javascript via document.write function and including script with it via src

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

    4 - pure ajax request that requests additional data and places it where it should be placed on the page

    5 - SSI (Server Side Include), as I mentioned it in comment

    6 - iframes (not the best way, though)

    7 - asp/jsp server script include (as alternative to php server script include)

    More info here:

    Common Header / Footer with static HTML

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

    Hopefully you can find the best way that will suit your needs from one of this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛