How to open a server file with javascript?

1

I have this code that opens a local file, but I would like to open a file from the server without needing input.

HTML:

<input type="file" onchange="run(this.files[0]);">

Javascript:

function run(file) {
    xyz.loadRomFromFile(file, function(result) {
        if (result) {
            for (var i = 0; i < runCommands.length; ++i) {
                runCommands[i]();
            }
            runCommands = [];
            xyz.runStable();
        }
    });
}
    
asked by anonymous 05.02.2015 / 12:06

2 answers

1

What you can do is an asynchronous call to the server. For example, to read a html file that is on the server, you can do this:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        // codigo
        document.getElementById('conteudoDoMeuArquivo').innerHTML = xhr.responseText;
    }
}

xhr.open('GET', 'caminho/para/meu/arquivo.html', true);
xhr.send();

If you're using the jQuery library, it's a little easier =):

$.get('caminho/para/meu/arquivo.html', function(data) {
    // codigo
    $('#conteudoDoMeuArquivo').html(data);
});
    
05.02.2015 / 12:54
0

It is possible, but it is not elementary.

As already mentioned, JS runs on the client, so you should do a service that receives the name of the file you want to open and returns your content. This service can be REST or it can be a server side script, type PHP, ASP, Node.js or Java Servlet. Anyway.

After that you should consume this service using http-request.

    
05.02.2015 / 12:46