2013-04-30 185 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