简体   繁体   English

AJAX请求后的函数调用在javascript中不起作用

[英]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. 有关信息,这些功能在2个文件中。

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. 基本上,您将函数作为参数传递,以便您可以在ajax(异步)完成时运行该函数。 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;
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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