例えば適用することができますここであなたが軌道に乗るかもしれないいくつかのコードです。
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);
}
出典
2012-01-10 14:31:54
ken
なぜJavascriptが必要ですか? –
ユーザーがJavascriptを無効にしている場合(NoScriptなど...)、それは機能しません。私もJavascriptを使った経験はあまりありません。 – Mac
JavaScript(あと、XMLHttpRequest)がなければ使用できません。ユーザーがJavaScriptを無効にしている場合は、入力してからEnterキーを押してから、ページ全体が読み込まれるのを待っているという劣った経験ができます。彼らはJavaScriptを有効にしている場合、彼らは –