我知道这已被问过好几次了,我已经阅读了几个关于回调的答案,但我仍然很困惑如何应用我的情况。我在第二个ajax函数的成功中调用了ajax函数。嵌入式ajax的结果总是未定义的。
Jquery的:
$('#mergeModal').on('show.bs.modal', function (e) {
// get the list of groups
$.ajax({
type: "GET",
url: '@Url.Action( "GetGroups", "Tally" )',
data: { contractId: $("#contractId").val() },
success: function (data) {
// empty then refill groups table
$("#groupsTable tbody").empty();
for (var key in data.groups) {
var groupParts = data.groups[key].split("::");
$("#groupsTable tbody").append("<tr id='" + groupParts[0] + "'><td>" + groupParts[1] + "</td><td>" + groupParts[2] + "</td></tr>");
}
// highlight first row and show appropriate students in students table
$("#groupsTable tbody tr:first").css("background-color", "#FFFF7F");
var groupID = $("#groupsTable tbody tr:first").attr('id');
console.log("groupID: " + groupID);
var students = getStudents(groupID);
console.log("students: " + students);
if(students != "false") {
for(var student in students.sellers) {
console.log(student);
}
}
这是getStudents函数:
function getStudents(group) {
$.ajax({
type: "GET",
url: '@Url.Action( "GetSellers", "Tally" )',
data: { groupId: group, contractId: $("#contractId").val() },
success: function (data) {
return data;
},
error: function() {
return "false";
}
});
}
答案 0 :(得分:0)
问题隐藏在getStudents
函数中,因为该函数不返回任何值。 ajax调用中的两个返回将异步触发。但是您可以添加自己的回调参数/函数来获取所需的数据。
function getStudents(group, callback) {
$.ajax({
type: "GET",
url: '@Url.Action( "GetSellers", "Tally" )',
data: { groupId: group, contractId: $("#contractId").val() },
success: function (data) {
callback(data);
},
error: function() {
callback(false);
}
});
}
然后这就是你如何称呼它的方式:
$('#mergeModal').on('show.bs.modal', function (e) {
// get the list of groups
$.ajax({
type: "GET",
url: '@Url.Action( "GetGroups", "Tally" )',
data: { contractId: $("#contractId").val() },
success: function (data) {
// empty then refill groups table
$("#groupsTable tbody").empty();
for (var key in data.groups) {
var groupParts = data.groups[key].split("::");
$("#groupsTable tbody").append("<tr id='" + groupParts[0] + "'><td>" + groupParts[1] + "</td><td>" + groupParts[2] + "</td></tr>");
}
// highlight first row and show appropriate students in students table
$("#groupsTable tbody tr:first").css("background-color", "#FFFF7F");
var groupID = $("#groupsTable tbody tr:first").attr('id');
console.log("groupID: " + groupID);
getStudents(groupID, function(students) {
console.log("students: " + students);
if(students != false) {
for(var student in students.sellers) {
console.log(student);
}
}
});
// ...
如您所见,在调用getStudents
函数时,您不会立即获得返回值,但是您将为其提供一个匿名函数,该函数将在getStudents
函数之后立即调用完成它的逻辑并将分享一些结果 - 它将作为你的匿名/回调函数的参数提供。