[英]Function call after AJAX request does not work in 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個文件中。
在這里,回調是一個好主意。 基本上,您將函數作為參數傳遞,以便您可以在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;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.