Uncaught ReferenceError: rand_linea is not defined at HTMLInputElement.onclick

0

Someone could tell me why I get the error "Uncaught ReferenceError: rand_linea is not defined at HTMLInputElement.onclick" I fixed everything and can not find the why, thanks for reading!

<!DOCTYPE html>
<html>
<script language="javascript" type="text/javascript"></script>

<body>
    <script>
function test() {
    alert();
    var arrayData = new Array();
    var archivoTxt = new XMLHttpRequest();
    var fileRuta = 'archivo.txt'
    archivoTxt.open("POST",fileRuta,false);
    archivoTxt.send(null);
    for (var i = 0; i < txt.length; i++ {
        arrayData.push(txt[i]);
    }
    arrayData.forEach(function(data){
        console.log(data);
    });
    var txt = archivoTxt.responseText;
    var rand_archivo = (fileRuta);
    var rand_contenido = (rand_archivo);
    var rand_linea = (rand_contenido);
}
    </script>
<form><input type="button" value="clickaqui" onclick="alert(rand_linea)">
</form>
</body>


</html>
    
asked by Pablosqui 24.11.2018 в 19:22
source

1 answer

0

The error jumps because when the browser reads the html file it tries to identify the code and finds that the variable rand_linea at that moment has no value.

In order to use the variable rand_linea as a global variable, you have to declare it outside the function. It is also not possible to add a variable JavaScript to the code html , so you will have to call a function from the onclick method.

The code should look something like this:

<!DOCTYPE html>
<html>
<script language="javascript" type="text/javascript"></script>
<body>
    <script>

      var rand_linea = "";

      function test() {
          alert();
          var arrayData = new Array();
          var archivoTxt = new XMLHttpRequest();
          var fileRuta = 'archivo.txt'
          archivoTxt.open("POST",fileRuta,false);
          archivoTxt.send(null);
          for (var i = 0; i < txt.length; i++ {
              arrayData.push(txt[i]);
          }
          arrayData.forEach(function(data){
              console.log(data);
          });
          var txt = archivoTxt.responseText;
          var rand_archivo = (fileRuta);
          var rand_contenido = (rand_archivo);
          rand_linea = (rand_contenido);
      }

      function notificacion(){
         alert(rand_contenido);
      }
    </script>
<form><input type="button" value="clickaqui" onclick="notificacion()">
</form>
</body>


</html>
    
answered by 24.11.2018 в 19:51