V
V
Victorius132019-01-16 22:54:31
JavaScript
Victorius13, 2019-01-16 22:54:31

Why is the JSON variable not being read outside of the main function?

Why if writing document.write(); outside the request.onload = function() function, nothing appears on the page and the error "Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()" appears in the console.

<html>
  <head>
    <title>Страница</title>
  </head>
  <body>
    <script>
  var data;
  var p = 'Victorius19';
    var request = new XMLHttpRequest();
    request.open('GET', 'https://api.vime.world/user/name/' + p, true);
    request.onload = function() {
        data = JSON.parse(request.responseText);
    
    //document.write("<" + data[0].guild.tag + "> " + "["+ data[0].rank + "] " + data[0].username);
    ;
    request.send();
  
  document.write("<" + data[0].guild.tag + "> " + "["+ data[0].rank + "] " + data[0].username);
    </script>
  </body>
</html>

Thanks in advance for your reply!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zendor, 2019-01-16
@Victorius13

There are two mistakes here. Firstly, the function does not have a closing curly brace, and secondly, this is an asynchronous request, so you are in at the time of the call . data //undefineddocument.write()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question