我有jquery代码,可以根据工作日从中获取数据报告。
我想要读取ajax返回的数组对象。
这是脚本:
<script>
export default {
data() {
return {
currentcohortgraphdata: [{"Monday":"0","Tuesday":"0","Wednesday":"0","Thursday":"0","Friday":"0","Saturday":"0","Sunday":"0"}],
}
},
mounted() {
},
methods: {
loadCohortAttendancies() {
this.$Progress.start();
axios.get("api/loadCohortAttendancies").then(({data}) => (this.currentcohortgraphdata = data));
this.$Progress.finish();
var result = this.currentcohortgraphdata;
result.forEach(function (e) {
if (e.Monday > 0) {
alert(e.Thursday);
}
});
}
},
created() {
this.loadCohortAttendancies();
},
mounted() {
}
}
当我从ajax请求axios.get("api/loadCohortAttendancies").then(({data}) => (this.currentcohortgraphdata = data));
运行上述脚本时,请求返回的结果为[{"Monday":"12","Tuesday":"10","Wednesday":"3","Thursday":"5","Friday":"4","Saturday":"1","Sunday":"9"}]
。但是不幸的是,当我运行脚本时,没有从脚本的alert(e.Thursday);
部分得到结果,有人可以指出我在哪里出错吗?预先感谢
答案 0 :(得分:0)
发生的事情是,您在请求完成之前就在运行代码,这导致使用默认值运行forEach
当前队列数据: [{{“ Monday”:“ 0”,“ Tuesday”:“ 0”,“ Wednesday”:“ 0”,“ Thursday”:“ 0”,“ Friday”:“ 0”,“ Saturday”:“ 0”, “ Sunday”:“ 0”}],
只需将您的代码移到.then块内
axios.get("api/loadCohortAttendancies").then(({data}) => {
this.currentcohortgraphdata = data
this.$Progress.finish();
var result = this.currentcohortgraphdata;
result.forEach(function (e) {
if (e.Monday > 0) {
alert(e.Thursday);
}
});
});
或者,您可以使用async/await语法:
methods: {
async loadCohortAttendancies() {
this.$Progress.start();
const { data } = await axios.get("api/loadCohortAttendancies");
this.currentcohortgraphdata = data;
this.$Progress.finish();
const result = this.currentcohortgraphdata;
result.forEach(function (e) {
if (e.Monday > 0) {
alert(e.Thursday);
}
});
}
},
答案 1 :(得分:0)
由于JavaScript是异步的,因此result.forEach
在axios请求完成之前正在运行。您可以通过简单地将依赖于设置的currentcohortgraphdata
的代码块移动到设置数据的代码块之后的另一个.then()
块中来解决此问题。像这样:
loadCohortAttendancies() {
this.$Progress.start()
axios.get("api/loadCohortAttendancies")
.then({data} => this.currentcohortgraphdata = data)
.then(() => {
this.$Progress.finish();
var result = this.currentcohortgraphdata
result.forEach(e => {
if (e.Monday > 0) {
alert(e.Thursday)
}
})
})
}
答案 2 :(得分:0)
执行forEach时,1
请求方法尚未执行。
因此,请更改您的代码,然后尝试这样
axios.get