下面的代码工作正常。我想处理错误情况,例如如果服务器的结果是null对象或搜索时出现一些数据库错误,我应该如何捕获错误并显示一些消息?
var nameIdMap = {};
$('#selectAgent').typeahead({
source: function (query, process) {
var that = this;
return $.ajax({
dataType: "json",
url: '/eBus/EbusinessAgentServlet',
data: 'q=' + query +"&task=tab1&AgentId=1234",
type: 'POST',
beforeSend: function() {
//that.$element is a variable that stores the element the plugin was called on
that.$element.addClass('loading');
},
complete: function() {
that.$element.removeClass('loading');
},
success: function (json) {
console.log(json)
process(getOptionsFromJson(json));
}
});
},
minLength: 2,
updater: function (item) {
console.log('selected id'+nameIdMap[item]);
return item;
}
});
});
function getOptionsFromJson(json) {
$.each(json, function (i, v) {
nameIdMap[v.fname + " "+ v.lname + " " + v.agentID] = v.agentID;
});
return $.map(json, function (n, i) {
return n.fname +" " + n.lname+" " + n.agentID;
});
}
答案 0 :(得分:0)
您可以使用fail()
方法或statusCode
选项进行错误处理,如下所示:
return $.ajax({
dataType: "json",
url: '/eBus/EbusinessAgentServlet',
data: 'q=' + query +"&task=tab1&AgentId=1234",
type: 'POST',
beforeSend: function() {
//that.$element is a variable that stores the element the plugin was called on
that.$element.addClass('loading');
},
complete: function() {
that.$element.removeClass('loading');
},
success: function (json) {
console.log(json)
process(getOptionsFromJson(json));
})
.fail(function() {
alert( "error" );
});
return $.ajax({
dataType: "json",
url: '/eBus/EbusinessAgentServlet',
data: 'q=' + query +"&task=tab1&AgentId=1234",
type: 'POST',
beforeSend: function() {
//that.$element is a variable that stores the element the plugin was called on
that.$element.addClass('loading');
},
complete: function() {
that.$element.removeClass('loading');
},
success: function (json) {
console.log(json)
process(getOptionsFromJson(json));
}
statusCode: {
404: function() {
alert( "page not found" );
}
});
我希望它有所帮助。