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

Function call after AJAX request does not work in javascript

本文关键字:javascript 不起作用 函数调用 请求 AJAX      更新时间:2023-09-26

我有一个警报工作的函数:

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);                                             
}

然后我有另一个函数,其中第一个被调用,相同的警报不起作用:

function Start(){
    var MyCard = RequestNext();
    alert("Patience.js");
    **alert(MyCard.GetNo());**
    alert("test2");
    //alert(Card.GetKind());
    //WriteCard(Card);
    alert("test3");
}

对于信息,这些函数在2个文件中

这就是回调的绝妙之处。基本上,您将一个函数作为参数传递,这样您就可以在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;
  });
}