XHR in javascript for Python displays three times the return [closed]

0

Recently I deployed Python on my IIS server, and started testing some requests. First I created the javascript code, as you can see below:

    sendRequest = function() {
        var http = new XMLHttpRequest();
        http.onreadystatechange = function() {
            if (this.readyState = 4 && this.status == 200) {
                console.log("ok!");
                var response = this.responseText;
                console.log(response);
            }
        };
        http.open("GET", "test.py", true);
        http.send();
        console.log("called");
    }  

The test.py file has the following code:

 print('Content-Type: text/plain')
 print('')
 print('Hello!')
 print('Hi')

However, the output I get on the console is:
ok! (nothing)
ok! Hello!
Hi
ok! Hello!
Hi

As far as I tested, the sendRequest function is only executed once, and I have found that the onReadyStateChange function is executed three times, why?

Can anyone tell me why this happens? Any help is appreciated.

    
asked by anonymous 10.03.2017 / 23:19

2 answers

2

Maybe the problem is your if that is wrong:

if (this.readyState = 4

When the correct one should be:

if (this.readyState == 4

So:

sendRequest = function() {
    var http = new XMLHttpRequest();
    http.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log("ok!");
            var response = this.responseText;
            console.log(response);
        }
    };

    http.open("GET", "test.py", true);
    http.send();
    console.log("called");
};
    
11.03.2017 / 01:03
2

I believe the problem is in your if

if (this.readyState = 4 && this.status == 200) {

You are assigning 4 to this.readyState and verifying the connection status to 200.

As the state of the connection changes during the request, the readyStateChange event will be called 4 times, in only 3 of these status is 200, so it executes 3 times

Do this:

sendRequest = function() {
    var http = new XMLHttpRequest();
    http.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log("ok!");
            var response = this.responseText;
            console.log(response);
        }
    };
    http.open("GET", "test.py", true);
    http.send();
    console.log("called");
}  
    
11.03.2017 / 01:04