Here is the Javascript equivalent to file_get_contents("filename.html")

This Javascript function is performs in the same way as the PHP function file_get_contents($filename) for files on the same server. It could work for files on another server if that site has CORS (cross site scripting) enabled. The different variations of the file_get_contents function let you return the file as a string, or as a data file into an element Id, or into a variable.

Also see Dynamically Load Content Without AJAX for an alternate method of loading data into a variable.

// return the file as a string just like the php file_get_contents()

function file_get_contents(filename) {
    fetch(filename).then((resp) => resp.text()).then(function(data) {
        return data;
    });
}

// or put the string directly into an html element

function file_get_contents(filename) {
    fetch(filename).then((resp) => resp.text()).then(function(data) {
        document.getElementById("inbox").innerHTML = data;
    });
}

// or load the string into a variable

function get(filename) {
    fetch(filename).then((resp) => resp.text()).then(function(data) {
        temp = data;
    });
}

Javascript Examples:

Example 1: returns the contents of textTest.txt into the div element with id "elementID"

document.getElementById("elementID").innerHTML = file_get_contents("textTest.txt");

Example 2: returns the contents of textTest.txt into a variable named "jsVar"

jsVar = file_get_contents("textTest.txt");


Both javascript examples above use this function to return a string the same way as the PHP function file_get_contents($filename)

function file_get_contents(filename) {
    fetch(filename).then((resp) => resp.text()).then(function(data) {
        return data;
    });
}

 

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use