在我看来,您有两个选择。
第一个是创建一个辅助函数来为您映射结果。这可能是最好/最简单的解决方案。简单代码:
$( "#birds" ).autocomplete({
minLength: 2
source: function (request, response) {
$.getJSON("search.svc/GetBirds", request, function (data, status, xhr) {
if (status == "success")
handleResponse(data); //you write this function
}
}
});
第二个选项是您可以通过"monkeypatch" 和AutoComplete plugin 函数来覆盖默认行为。
因此,在您的情况下,您想要覆盖 $.ui.autocomplete.prototype._initSource 函数。这里的公平警告是,您基本上覆盖了 UI 库中的核心函数,如果该库被更新,您的函数将始终覆盖它。
// Create a closure so that we can define intermediary
// method pointers that don't collide with other items
// in the global name space.
function monkeyPatchAutocomplete() {
// don't really need this, but in case I did, I could store it and chain
var oldFn = $.ui.autocomplete.prototype._renderItem;
var requestIndex = 0;
$.ui.autocomplete.prototype._initSource = function() {
// whatever
console.log("Override method");
var self = this,
array, url;
if ($.isArray(this.options.source)) {
array = this.options.source;
this.source = function(request, response) {
response($.ui.autocomplete.filter(array, request.term));
};
} else if (typeof this.options.source === "string") {
url = this.options.source;
this.source = function(request, response) {
if (self.xhr) {
self.xhr.abort();
}
self.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
autocompleteRequest: ++requestIndex,
success: function(data, status) {
console.log("Override success function, handling request");
if (this.autocompleteRequest === requestIndex) {
response(data); //you handle both types of data here
}
},
error: function() {
console.log("Override error function, handling request");
if (this.autocompleteRequest === requestIndex) {
response([]);
}
}
});
};
} else {
this.source = this.options.source;
}
};
}
// When DOM is ready, initialize.
$(document).ready(function() {
monkeyPatchAutocomplete();
$("#birds").autocomplete({
source: "http://jqueryui.com/demos/autocomplete/search.php",
minLength: 2
});
});
然后您的代码不需要执行任何不同的操作,它只是处理差异并将其传递给成功方法。
这里是一个 jsFiddle:http://jsfiddle.net/lemkepf/DAQ6s/5/ 注意: 实际的自动完成不会工作,因为跨域安全已经到位。当您开始在框中输入内容时,您可以打开 firebug 并查看 console.debug 行。