首页 > 解决方案 > 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 造成的,但我不知道如何解决这个问题。以前有没有人遇到过这个问题?

标签: javascriptajax

解决方案


推荐阅读