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

标签 javascript php html

在 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 文件,但您可以为此创建一个辅助函数。

Following this tutorial你将能够得到这样的东西:

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;
    }
  }
};

关于javascript - 如何在js文件中包含html文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607495/

相关文章:

javascript - 如何使用 jQuery 制作一个简单的切换按钮

php - 对 Symfony 服务类进行单元测试

javascript - 在 HTML/CSS 中分层 PNG?

html - 在 div 中包装一个没有空格的单词

php - 如何克服TCPDF ERROR : [Image] Unable to get image?

html - HTML 中的 valign 与 text-align

javascript - 延迟加载和解析 PrimeFaces JavaScript 文件

javascript - SetTimeout 和 For 循环

javascript - 水平滚动 div CSS 中的 float 可见 div

PHP 5.5,如何启用 mysql_connect()?