简体   繁体   中英

Method in class not being called after XMLHttpRequest is done

I have the following method to log into my API:

login()
{
    var formData = new FormData();

    formData.append("admin[email]", "user");
    formData.append("admin[password]", "pass");

    var request = new XMLHttpRequest();
    request.open("POST", "my_link");

    request.onreadystatechange = (function() {
      if (request.readyState === XMLHttpRequest.DONE && request.status === 201)
      {
        return function() { this.loadMembers(); }
      }
    });

    request.send(formData);
  }

Then I have my method that I'm trying to call AFTER my post async request is completely done:

loadMembers()
{
    ....
}

Now for some reason, this.loadMembers() is never being called. If I put a testing console.log() right above it (not within the return callback) it calls just fine - so I know that the requestState and request status is correct.

Is there a better way to do this? Or what am I doing wrong?

Thanks

It is because you are returning a function instead of just calling loadMembers.

So instead of:

request.onreadystatechange = (function() {
  if (request.readyState === XMLHttpRequest.DONE && request.status === 201)
  {
    return function() { this.loadMembers(); }
  }
});

You likely want:

var that = this;
request.onreadystatechange = (function() {
  if (request.readyState === XMLHttpRequest.DONE && request.status === 201)
  {
    that.loadMembers();
  }
});

请记住,login()中的“ this”与(function(){if ....})中的“ this”不同,因此您需要以rasmeister所显示的方式保存= this的var。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM