0

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.

4

1 回答 1

0

这就是回调是个好主意的地方。基本上,您将一个函数作为参数传递,这样您就可以在 ajax(这是异步的)完成时运行该函数。这里的语法可能略有偏差,但您可以执行以下操作:

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;
  });
}
于 2013-04-30T01:20:06.813 回答