我正在寻找一种在ajax调用后初始化var的方法。问题在于ajax调用在另一个文件中。
这是我的代码:
file1.js
$(document).ready(function () {
getKanbans();
});
function getKanbans() {
var kanbans = RequestSender.getKanbans();
console.log(kanbans); // print undefined
}
RequestSender.js
class RequestSender {
static getKanbans() {
$.ajax({
url: './ajax/select_kanbans.php',
type: 'GET',
success: RequestSender.initKanbanList
});
}
static initKanbanList(data) {
var result = JSON.parse(data);
var kanbans = [];
for (var i = 0; i < result.kanbans.length; ++i) {
var currentKanban = result.kanbans[i];
kanbans.push(new Kanban(currentKanban['Name'], currentKanban['Status']))
}
console.log(kanbans); // correctly displayed
return kanbans;
}
}
我只使用jQuery,所有文件都包括在内。我认为问题出在ajax是异步的,但我不知道如何解决。
答案 0 :(得分:0)
这在javascript中称为模块。您可以直接使用链接标记实现它们。但是RequireJS之类的库为您提供了更好的服务。然后您可以执行以下操作:
require(['./RequestSender'], function (RequestSender) {
var rs = new RequestSender();
... //whatever
});
这里有一个很好的SO问题,可以很好地解释模块:How do I include a JavaScript file in another JavaScript file?
答案 1 :(得分:0)
在您的示例ajax调用已开始,但看板仍未定义
function getKanbans() {
//ajax call started but kanbans still undefined
var kanbans = RequestSender.getKanbans();
console.log(kanbans); // print undefined
}
所以您应该在ajax调用完成后完成执行,您可以在promises的帮助下完成
for more information Check this
function getKanbans(url) {
var promiseObj = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("xhr done successfully");
var response = xhr.responseText;
var responseJson = initKanbanList(response);
resolve(responseJson);
} else {
reject(xhr.status);
console.log("xhr failed");
}
} else {
console.log("xhr processing going on");
}
}
console.log("request sent succesfully");
});
return promiseObj;
}
function initKanbanList(data) {
var result = JSON.parse(data);
var kanbans = [];
for (var i = 0; i < result.kanbans.length; ++i) {
var currentKanban = result.kanbans[i];
kanbans.push(new Kanban(currentKanban['Name'], currentKanban['Status']))
}
console.log(kanbans); // correctly displayed
return kanbans;
}
$(document).ready(function () {
// to call it
getKanbans('./ajax/select_kanbans.php').then(function (kanbans) {
console.log(kanbans);
}, function (error) {
console.log(error);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>