javascript - ajax设置后类属性未定义
问题描述
我想通过 ajax 设置一个 Class 属性。该代码对我有用:
class SweetCalendar{
constructor(){
this.getEmployees();
}
getEmployees(){
let url = window.location.protocol + "//" + window.location.host + '/api/v1/employeelist/';
$.ajax({
type: "GET",
url: url,
context: this,
success: function (result, status, xhr) {
this.employees = result;
},
timeout: 120000,
});
}
当我用
var a = new SweetCalendar()
console.log(a.employees)
我收到了预期的一系列员工。现在我想用类中的测试函数迭代这个属性:
class SweetCalendar{
constructor(){
this.getEmployees();
}
test(){
for(i of this.employees){
console.log(i)
}
}
getEmployees(){
let url = window.location.protocol + "//" + window.location.host + '/api/v1/employeelist/';
$.ajax({
type: "GET",
url: url,
context: this,
success: function (result, status, xhr) {
this.employees = result;
},
timeout: 120000,
});
}
var a = new SweetCalendar();
a.test();
这行不通。this.employees 未定义。我认为这是由于异步 ajax 造成的,但我不知道如何解决这个问题。以前有没有人遇到过这个问题?
解决方案
推荐阅读
- android - Lollipop vs Nougat Runtime 目录权限到外部存储文件夹
- jquery - 下拉焦点无法按预期对后代元素起作用
- html - 代码块使用 PdfMake 破坏 pdf
- unity3d - Unity - 无尽奔跑游戏中的障碍物通过检测
- mysql - 来自另一行的条件时 SQL 更新表
- android - 构建错误,在构建 gradle 中混合版本
- ansible - 使用 Ansible 停止可能不存在的服务
- r - 闪亮的模块导入数据并在成功时隐藏 html
- javascript - React Native v0.56:无法读取 PluginPass.JSXOpeningElement 处未定义的属性“文件名”
- php - 如何在 PHP 中创建 wordpress 帖子时以编程方式和动态添加 CSS 和 JS