【问题标题】:Function call after AJAX request does not work in javascriptAJAX请求后的函数调用在javascript中不起作用
【发布时间】:2013-04-30 00:05:46
【问题描述】:

我有一个警报正在起作用的功能:

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 个文件中。

【问题讨论】:

  • 这是异步编程的陷阱。这是一个如此常见的 SO 问题,我想找到一篇非常好的博客文章来涵盖它并将人们链接到它。到目前为止还没有找到。
  • 您的 RequestNext() 函数没有 return 语句。只有你的内部匿名函数有一个return。所以即使忽略异步问题,这段代码也不起作用。
  • 我理解这两个评论,但我不知道如何才能完成这项工作。有没有办法在处理我的其余代码之前等待 Ajax 完成?
  • 我可能会使用一个回调函数,该函数将从您当前拥有 return 语句的位置调用。 (不幸的是,我在我的手机上写了这个评论,在这里输入实际代码太难了;如果到那时你还没有得到另一个答案,我会在今晚(澳大利亚时间)用我的笔记本电脑为你输入一些东西。 )
  • 非常感谢,我已经得到了你所说的例子。这是个好主意!!!

标签: javascript ajax return


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-03-15
    • 1970-01-01
    • 2017-09-11
    • 2014-12-16
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    相关资源
    最近更新 更多