简体   繁体   中英

Is there a way to create and modify HTML and Javascript files dynamically?

I have a project whose requirements have been consistently expanding. At first, it was fine because I could hard code most of it. However, I find that I am making different versions of the same type of forms and programming specific JS files to go along with them. Is there a way to dynamically create an HTML and JS file? So, maybe I could write a function or something that reads requirements from a text files, and from that, build an HTML file, a JavaScript file, and modify other JavaScript files within the directory. For example:

Say I have a JS file named main.js

   /* I hold all the basic requirements and functions for every form*/
   var blueForm = ...
   var redForm = ...

There currently exists HTML files named blueForm.html and redForm.html. I want to add a function to main.js such that:

   function createNewForm(requirements){
        . . .
        createHTML();
        createJS();
        modifyMain(this); /* as in this file (main.js) */
        . . .
        if(successful){ return 0; }
        return 1;
   }

Now main.js should have been modified like:

   var blueForm = ...
   var redForm = ...
   var greenForm = ...

And now there exists HTML files named blueForm.html, redForm.html, and greenForm.html.

The answer is yes. The most accessible way of doing this is using php, most commonly implemented through a Linux / Apache / MySQL / PHP stack (LAMP). HTML and JS be easily injected into a file your browser reads as html.

Here's a sample.php file:

<html>
<body>
<?php
    echo "Hello World";
    echo "<script>";
    $myvar = 1;
    if ($myvar==1) {
        echo "function dosomethingjavascripty() {";
        echo "console.log('doing it');";
        echo "}";
    }
    echo "</script>";
?>
</html>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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