如何从异步方法(ajax)中获取值



我不习惯异步方法,所以我想有你的帮助。我有这个ajax方法来获取mysql表的数据。我需要检索这些数据,以便在我的代码中使用它。

下面是我的代码:
function ajaxRequest(type,url,callback,data=""){
let request = new XMLHttpRequest();
request.open(type, url);
request.onload = function () {
switch (request.status){
case 200:
case 201: //console.log(request.responseText);
callback(request.responseText);
break;
default: console.log(request.status);
}
};
request.send(data);
}
function setAvailableQuestions(){
ajaxRequest("GET","../controller.php?func=get_availableQuestion", (questions) => {
var allQuestions = JSON.parse(questions);
return allQuestions;
});
}
function getNewQuestion(){
var availableQuestions = setAvailableQuestions();
console.log(availableQuestions); //undefined

}

我读到你可以用两种不同的方式来解决它,第一种是将ajax请求异步设置为false:

function setAvailableQuestions(){
var ajax = new XMLHttpRequest();
var asynchronous = false;
ajax.open("GET","../controller.php?func=get_availableQuestion", asynchronous);
ajax.send();
ajax.onreadystatechange = function(){
var allQuestions = JSON.parse(this.response);
return allQuestions;
}
}

function getNewQuestion(){
var availableQuestions = setAvailableQuestions();
console.log(availableQuestions); //undefined
}

但是它仍然显示未定义另一个方法是使用。then或await异步方法,但我不知道如何将它应用到我的第一个代码。

有谁能帮我吗?

尝试设置" return ";在setAvailableQuestions () .

function setAvailableQuestions(){
var ajax = new XMLHttpRequest();
var asynchronous = false;
ajax.open("GET","../controller.php?func=get_availableQuestion", asynchronous);
ajax.send();
ajax.onreadystatechange = function(){
var allQuestions = JSON.parse(this.response);
return allQuestions;
}
return ajax.onreadystatechange;
}

相关内容

  • 没有找到相关文章

最新更新