为什么readyState == 0不起作用

So my problem is that when I'm using if(this.readyState == 0) It doesn't do its job. I hava e script that loads form with ajax and I have the option to close the form, but then i realised that if i want to open that form again without making new ajax request i would need somekind of variable for it. I have variable called "isOpen" and when xhr readyState is 0 i want it to check if isOpen is true and in case if its true it aborts xhr and shows the form data. Right now it doesn't seem to work as i expected it to.

Here is my whole function for handling this AJAX request.

function postPlacesForm() {
var yhteys = new XMLHttpRequest();
yhteys.onreadystatechange = function() {
    var isOpen = false;
    if(this.readyState === 0) {
        if(isOpen === false) {

        }
        else if(isOpen === true) {
            document.getElementById("places").style.display = "block";
            yhteys.abort();
        }
    }
    if(this.readyState === 4 && this.status === 200) {
        document.getElementById("places").innerHTML = this.responseText;
        document.getElementById("places").style.display = "block";
        document.getElementById("ajax_close").style.display = "block";
        isOpen = true;
    }

};
yhteys.open("POST", "/js/ajax_inc/forms/postplaces.php", true);
yhteys.send();

}

It looks that you don't understand the readyState property yet.

  • 0 UNSENT Client has been created. open() not called yet.
  • 1 OPENED open() has been called.
  • 2 HEADERS_RECEIVED send() has been called, and headers and status are available.
  • 3 LOADING Downloading; responseText holds partial data.
  • 4 DONE The operation is complete.

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

Okey i got it working somehow with readyState 2. Thank you all and i'm sorry for wasting your time.

Solution code down below

var postPlaceFormIsOpen = 0;
function postPlacesForm() {
    var yhteys = new XMLHttpRequest();
    yhteys.onreadystatechange = function() {
        if(this.readyState === 2) {
            if(postPlaceFormIsOpen === 0) {

            }
         else {
            yhteys.abort();
            console.log("test");
            document.getElementById("places").style.display = "block";
            document.getElementById("ajax_close").style.dispaly = "block";
        }
    }
    if(this.readyState === 4 && this.status === 200) {
        document.getElementById("places").innerHTML = this.responseText;
        document.getElementById("places").style.display = "block";
        document.getElementById("ajax_close").style.display = "block";
        postPlaceFormIsOpen++;
        console.log(postPlaceFormIsOpen);
    }

};
yhteys.open("POST", "/js/ajax_inc/forms/postplaces.php", true);
yhteys.send();

}