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 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名