这里有一些代码可以帮助你。
它使用 jquery Javascript 库。它假定您正在获取要显示给用户的结果列表的完整 HTML。您将需要更多 Javascript 来动态显示/隐藏包含列表的框。您还需要一个服务器端脚本,该脚本可以根据某些搜索文本获取搜索结果的集合。该脚本应位于 #searchPartialUrl 标记中定义的 URL(可以隐藏)。搜索文本应位于名为 #searchText 的输入中。
我喜欢这种方法,因为您可以将 JS 代码保存在单独的文件中并重复使用。您的服务器只需要创建在常规 HTML 标记中包含所有异步目标信息的 HTML 视图。
我还在检查键事件之间实现了延迟,这样您就不会不断地向服务器发送请求。 (我从 stackoverflow 上的另一个答案中得到了这个方法,但我现在似乎找不到它。我会在我这样做时给予信任。)
// This function is used to delay the async request of search results
// so we're not constantly sending requests.
var mydelay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
var asyncSearchForm = function(onSuccess) {
var keyupWrapper = function(keyCode) {
// if this key was an arrow key, then
// ignore the press
for (var i = 37; i <= 40; i++)
if (keyCode == i)
return;
// get all the search info from the form
var searchText = $('#searchText').val();
var searchPartialUrl = $('#searchPartialUrl').val();
// make the ajax call
$.ajax({
type: "POST",
url: searchPartialUrl,
data: {
searchText: searchText
},
dataType: "html",
// on success, the entire results content should be replaced
// by the results returned
success: function(data, textStatus, jqXHR) {
$('#searchResults').html(data);
onSuccess();
},
// on error, replace the results with an error message
error: function(jqXHR, textStatus, errorThrown) {
$('#searchResults').html('<p>An error occurred while getting the search results.</p>');
}
});
};
onSuccess = (typeof (onSuccess) == 'undefined') ? function() { } : onSuccess;
// On each key-up event, we'll search for the given input. This event
// will only get triggered according to the delay given, so it isn't
// called constantly (which wouldn't be a good idea).
$('#searchText').keyup(function(e) {
// delay between each event
mydelay(function() {
// call key up
keyupWrapper(e.keyCode);
}, 500);
});
}
更新:
您说您使用的是 C#。如果您使用的是 MVC,则需要控制器中的操作作为异步请求的目标。这是一个例子:
[HttpPost]
public ActionResult GetSearchResults(string searchText)
{
// Here, you should query your database for results based
// on the given search text. Then, you can create a view
// using those results and send it back to the client.
var model = GetSearchResultsModel(searchText);
return View(model);
}