繁体   English   中英

如何在js文件中包含html文件

[英]how to include html file inside js file

在php中,我这样写:

<?php include "file.php" ?>

在html文件中,我这样写:

<script src='file.js'></script>

现在,我正在处理一个js文件。

在这个js文件中,我想包含这样的html文件。

<script>
  code to include html file here 
  code to include html file here 
  code to include html file here 
  code to include html file here 
  code to include html file here 
  code to include html file here 
  code to include html file here 
</script>

非常感谢。

您不能在外部JS文件中调用HTML文件,但是可以为此创建一个辅助函数。

遵循本教程,您将能够获得以下内容:

function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = "filename.html";
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}

          //elmnt.innerHTML - THIS HTML FROM YOUR FILE
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM