2013-04-30 212 views
0

我有一个函数在警报工作:功能不能正常工作在JavaScript

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

+1

这是异步编程的问题。这是一个很常见的SO问题,我希望找到一篇非常好的博客文章,它涵盖了它并将人们链接到它。到目前为止没有找到一个。 – 2013-04-30 00:15:21

+1

您的_RequestNext()_函数没有_return_语句。只有你的内部匿名函数有一个_return_。所以即使忽略异步问题这个代码也不行。 – nnnnnn 2013-04-30 00:20:44

+0

我理解这两个评论,但我不明白我可以如何使这项工作。有没有办法在处理剩余的代码之前等待Ajax完成? – Pink 2013-04-30 00:27:38

回答

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

谢谢,这真的很有用! – Pink 2013-04-30 02:14:24