我使用ajax在一个数组中填充我的departmentName。在$ .each期间,departmentName有一个值,但在ajax结束后,当我记录departmentName时,它没有值。
$("#Search").click(function () {
var titleId = $("#title").val();
var departmentGenericId = $("#department").val();
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
var departmentName = [];
var complianceValue = [];
var nonComplianceValue = [];
var complianceRate = [];
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '/AcknowledgementAdminLevel/AcknowledgemetnComplianceRate/',
data: {"titleId": titleId,
"departmentGenericId" : departmentGenericId,
"startDate" : startDate,
"endDate" : endDate
},
dataType: "json",
success: function (data) {
$.each(data, function () {
departmentName.push(this.DepartmentName);
complianceValue.push(this.Compliance);
nonComplianceValue.push(this.NonCompliance);
complianceRate.push(this.ComplianceRate);
});
}
});
console.log(departmentName);
});
答案 0 :(得分:0)
正在异步调用ajax调用,因此在执行console.log语句时不会填充departmentName。如果你真的想通过添加async选项,你可以设置ajax调用同步执行,如下所示:
$.ajax({
async: false,
//...
选项。然后,ajax调用将等待响应,然后继续执行。