我不熟悉回调并尝试让它发挥作用。我不希望我的getCustomerIdDescription在我的帖子返回数据之前向我的popover返回任何内容,但是我在底部的'callback(supplierId)'行中出现错误,该行显示'回调不是函数'如何编写我的回调,以便在我获得我的帖子数据之前不会从getCustomerIdDescription返回任何内容?
这是我的代码
scope.showCustomerIdList = function(value) {
$('#{0}'.format(value)).popover({
html: true,
container: 'body',
content: function() {
return scope.getCustomerIdDescription(value);
},
title: function() {
return 'Customer ID - Description';
}
}).popover('show');
};
scope.getCustomerIdDescription = function(supplierId, callback) {
var model = {};
model.clientId = scope.contextClientId;
model.supplierId = supplierId;
$.post(scope.enumControllers.GetCustomerIdsForSupplier, model, function(response) {
if (response.error == false) {
var ids = JSON.parse(response.ids);
var list = '';
_.each(ids, function(result) {
list += '<li>' + result.CustomerId + ' - ' + result.CustomerDescription + '</li>';
});
return '<ul>' + list + '</ul>';
} else {
return "Cound't Fetch Customer Ids";
}
}).fail(function() {
return "Cound't Fetch Customer Ids";
});
callback(supplierId);
};
答案 0 :(得分:3)
你打电话:
scope.getCustomerIdDescription(value);
但你定义:
scope.getCustomerIdDescription = function(supplierId, callback) {
由于您未向其传递值,callback
为undefined
。
然后你:
callback(supplierId);
...没有进行测试以查看callback
是否为函数。
或者:
getCustomerIdDescription
顺便说一句,如果在发送Ajax请求后立即调用回调函数,则没有太多意义。将它放在您在请求中设置的回调函数中通常更有意义。
答案 1 :(得分:1)
为了使您的代码能够运行,请尝试以下方法,并了解 Asynchronicity 的方法和概念,请访问Asynchronicity
scope.showCustomerIdList = function(value) {
scope.getCustomerIdDescription(value, function(content){
$('#{0}'.format(value)).popover({
html: true,
container: 'body',
content: function() {
return content;
},
title: function() {
return 'Customer ID - Description';
}
}).popover('show');
});
}
scope.getCustomerIdDescription = function(supplierId, callback) {
var model = {};
model.clientId = scope.contextClientId;
model.supplierId = supplierId;
$.post(scope.enumControllers.GetCustomerIdsForSupplier, model, function(response) {
if (response.error == false) {
var ids = JSON.parse(response.ids);
var list = '';
_.each(ids, function(result) {
list += '<li>' + result.CustomerId + ' - ' + result.CustomerDescription + '</li>';
});
callback('<ul>' + list + '</ul>');
} else {
return "Cound't Fetch Customer Ids";
}
}).fail(function() {
return "Cound't Fetch Customer Ids";
});
};