Question

This is an odd one; This function is called by a timer every 1 second in Qt. Check out the if statement; first it parses some JSON data, then it logs that it is parsing. As I would expect, the console.log is only happening when fileshow.txt changes it contents. HOWEVER -- The line that says var parsed = JSON.parse(t) reports a parsing error every 1 second, even when nothing else (including the logging) occurs during that one second:

function get() {
    var xhr = new XMLHttpRequest;
    xhr.open("GET", "/fileshow.txt");
    xhr.onreadystatechange = function () {
        var t = xhr.responseText;
        if (t != tt.lastData) {
            var parsed = JSON.parse(t);
            console.log("parsing");

            viewer.newImages(parsed.files);
            thetime.shouldRepeat = parsed.repeat;
            thetime.fps = parsed.fps;
            tt.lastData = t;
            thetime.running = true;
        }
    }
    xhr.send()
}

Even though I get a parse error (which is a different topic -- the data is in fact parsing correctly despite the error, as it is getting routed via the above formulas just fine and other parts of the program get the data as expected), I should not even be seeing an error for that source code line unless that if branch actually runs! How can it report a parsing error that could only happen in that if branch when that if branch is not even running?!

There is no other parsing anywhere, and the error is reported for the specific line number of this JSON.parse call.

Était-ce utile?

La solution

If you're asking why the if statement executes, it's because onreadystatechange is called every time the state of the XHR request changes. There are 5 states for XHR:

  • 0: UNSENT (open() has not been called yet)
  • 1: OPENED (send() has not been called yet)
  • 2: HEADERS_RECEIVED (send() has been called and headers and status are available)
  • 3: LOADING (downloading; responseText holds partial data)
  • 4: DONE (operation complete)

Because onreadystatechange will be called when it starts loading, you're getting passed in a partial JSON file, which is extremely unlikely to validate as proper JSON. You need to check that the readyState is 4, that is, it has finished loading:

if (xhr.readyState === 4 && xhr.status === 200 && t != tt.lastData) {

You also probably want to check that the request was successful by checking for a HTTP 200 response. For more information about XMLHttpRequest, see this MDN article.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top