简体   繁体   中英

Function call after AJAX request does not work in javascript

I have a function where the alert is working:

function RequestNext() {

    var xhr = getXMLHttpRequest();

    xhr.onreadystatechange = function() {

        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            MyCard = GetCard(xhr.responseText);
            **alert(MyCard.GetNo());**
            return MyCard;
        }
    };

    xhr.open("GET", "../../HttpRequest_Next.php" , true);

    xhr.send(null);                                             
}

Then I have this other function where the first one gets called and the same alert does not work:

function Start(){

    var MyCard = RequestNext();

    alert("Patience.js");
    **alert(MyCard.GetNo());**
    alert("test2");
    //alert(Card.GetKind());
    //WriteCard(Card);
    alert("test3");
}

For information, those functions are in 2 files.

This is where a callback is a great idea. Basically you pass a function as an argument, so that you can then run that function when the ajax (which is asyncronous) completes. The syntax here may be slightly off, but you could do something like:

function RequestNext(callback) {

  var xhr = getXMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
        MyCard = GetCard(xhr.responseText);
        **alert(MyCard.GetNo());**
        if (typeof callback=='undefined') return MyCard;
        else {
          return callback.call(MyCard);
        }
    }
  };

  xhr.open("GET", "../../HttpRequest_Next.php" , true);

  xhr.send(null);                                             
}
function Start(){
  var MyCard = RequestNext(function() {
      alert("Patience.js");
      alert(this.GetNo());
      alert("test2");
      //alert(this.GetKind());
      //WriteCard(this);
      alert("test3");
      return this;
  });
}

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