【问题标题】:Rewrite HTML file using only JavaScript in header仅在标头中使用 JavaScript 重写 HTML 文件
【发布时间】:2018-08-12 12:51:01
【问题描述】:

我有一个包含此代码的 HTML 文件:

<html>

  <head>

    <script>

      function saveTextArea() {

        var newText = document.getElementById("textArea");

        <!-- rewrite this file with <textarea id = 'textArea'> newText </textarea> -->

      }

    </script>

  </head>

  <body>

    <button id = 'saveBtn'>Save</button>

    <br>

    <textarea id='textArea1'>MyText</textarea>

  </body>

</html>

我的用例是:在浏览器中,我重写了 textarea 中的内容。之后,我按下保存按钮。在那一刻,我想用 textarea 中的新文本重写我的 HTML 文件,这样在重新打开 HTML 文件时它将有一个新文本。

我想在没有额外文件的情况下这样做。可以仅在标头中使用 javascript 来完成吗?如果是,怎么做?

【问题讨论】:

  • 建议您为此使用服务器端语言。

标签: javascript html


【解决方案1】:

不,如果没有任何服务器端代码,这是不可能的,因为当浏览器请求文件(如http://localhost/index.html)时,服务器会返回文件index.html 的副本。如果您对 Document(DOM) 进行更新(通过 javascript),它将不会反映在原始位置。静态文件也是如此。即,file:///path/to/somefile.html

最后要注意的是,您无法在浏览器中使用 javascript 更新真实文件(somefile.html)您使用 javascript 进行的每次更新都是临时且非持久性的

【讨论】:

    【解决方案2】:

    如果我理解正确,您想在按下按钮时替换“Mytext”,然后在服务器上用替换后的文本保存新文件?

    首先你可以通过在你有命令的地方添加newText.innerHTML="new text here"来替换“Mytext”(https://www.w3schools.com/jsref/prop_html_innerhtml.asp)

    但是现在你不能只用 javascript 来保存它,而仅仅将整个页面发送到你的服务器并将其保存为 .html 将是一个糟糕的主意(永远不要相信用户输入,如果你要发送整个 .html您服务器上的文件已在其他人的计算机上被操纵...)

    我的建议是(但这取决于你想用它做什么):使用 SQL 来跟踪哪个用户保存了什么。并在使用 PHP 生成页面时检查用户是否之前保存过。

    【讨论】:

    • 这是我想要的,但是 html 文件不在服务器上。它在我的云端。
    • 它仍然很危险。例如:我可以创建一个 .php 文件,它将删除所有文件 [链接] (w3schools.com/php/func_filesystem_unlink.asp)。欺骗浏览器发送它,然后再次以正常方式请求它。根据请求,它将执行该功能并删除所有内容。
    【解决方案3】:

    如果您必须在没有服务器端代码且仅使用 javascript 的情况下执行此操作,我建议您使用 window.sessionStorage。虽然我不建议这样做,但为了您的学习过程,您可以这样做:

    <script>
    
    this.onload = function() { // You can either use this/window.onload, as we are selecting some element from DOM or place this script at the bottom of your body
      var newText = document.getElementById("textArea");
      var btn = document.getElementById("saveBtn");
    
      // First check if anything is saved, if so alter the innerHTML accordingly
      if (sessionStorage.getItem("isSaved")) {
        newText.innerHTML = "newText";
      }
    
      // Assign a function to the button to set the session then change innerHTML
      btn.onclick = function() {
        sessionStorage.setItem("isSaved", true);
        newText.innerHTML = "newText";
      }
    }
    
    </script>
    

    <button id = 'saveBtn'>Save</button>
    
    <br>
    
    <textarea id='textArea'>MyText</textarea>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 2017-03-27
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多