-2

I can't seem to figure out why this code won't display the JSON requested. I've narrowed this down to the bare minimum and still having issues. Am I not doing the XMLHttpRequest properly?

<html>
    <body>
            <a id="testname"></a>
            <a id="testval"></a>
    </body>
    <script>
        var request = new XMLHttpRequest();
        request.open('GET', 'test.json');
        request.responseType = 'json';
        request.send();
        request.onload = function() { 
            var test = request.response;
            document.getElementById("testname").innerHTML = test.name;
            document.getElementById("testval").innerHTML = test.val;
        };
    </script>
</html>
  • 1
    check console for any errors – Manos Kounelakis Feb 13 '18 at 23:23
  • @JaromandaX — It's `response`, not `responseText`. – Quentin Feb 14 '18 at 00:02
  • I can't reproduce the problem. The code works perfectly when I test it. The problem must be something you haven't mentioned in the question. Open the developer tools. Look at the Console. Are there any errors reported? What does the JSON look like? – Quentin Feb 14 '18 at 00:03
  • When I test with an external link like Morteza posted it does seem to work fine. I'm trying to access a local file test.json and I used jsonlint to verify the integrity of the Json. Is there something wrong with trying to access the local file as test.json? – Toomuchbob Feb 14 '18 at 00:11
  • "I'm trying to access a local file test.json" — Then you should get a very obvious error message and your question is a duplicate of https://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local – Quentin Feb 14 '18 at 00:13
  • `Is there something wrong with trying to access the local file as test.json` - yes, it won't work in some browsers (or any browsers these days) – Jaromanda X Feb 14 '18 at 00:49

1 Answers1

-1

I believe you are sending the request before setting the onload callback function. Most likely, the request is completing before you assign the callback function so nothing is happening. Check out this documentation on the send function: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

Reece Stevens
  • 444
  • 3
  • 7