반응형
AJAX: 폼 필드에 입력할 때 검색 지연
제 웹사이트에서 저는 JavaScript/AJAX를 사용하여 사용자가 타이핑을 하는 동안 검색을 하고 결과를 표시합니다.
HTML(본문):
<form action="" method="post" accept-charset="utf-8">
<p><input type="text" name="q" id="q" value="" onkeyup="doSearch(this.value)" /></p>
</form>
JavaScript(헤더):
function doSearch(text) {
// do the ajax stuff here
// call getResults.php?search=[text]
}
그러나 이로 인해 서버에 많은 요청이 발생할 수 있습니다.
따라서 지연을 설정하여 서버를 완화합니다.
onkeyup 이벤트가 발생할 때마다 doSearch() 함수는 "ajax loading graphic"을 표시하고 2초간 기다립니다.이 2초 동안 이벤트가 다시 시작되지 않는 경우에만 PHP 파일에서 결과를 가져와야 합니다.
어떻게 할 수 있을까요?도와주실 수 있나요?잘 부탁드립니다!
var delayTimer;
function doSearch(text) {
clearTimeout(delayTimer);
delayTimer = setTimeout(function() {
// Do the ajax stuff
}, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
}
setTimeout()을 사용하여 지연 호출을 설정하고 clearTimeout()을 사용하여 모든 이벤트에서 다시 호출을 삭제합니다.
HTML
<form action="" method="post" accept-charset="utf-8">
<p><input type="text" name="q" id="q" value="" onkeyup="doDelayedSearch(this.value)" /></p>
</form>
자바스크립트
var timeout = null;
function doDelayedSearch(val) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
doSearch(val); //this is your existing function
}, 2000);
}
이런 종류의 것을 위해 나는 Remy Sharp가 만든 교활한 작은 '썰매' 기능을 사용하는 경향이 있다.
http://remysharp.com/2010/07/21/throttling-function-calls/
언급URL : https://stackoverflow.com/questions/7849221/ajax-delay-for-search-on-typing-in-form-field
반응형
'programing' 카테고리의 다른 글
| react-router-dom v4의 여러 네스트 루트 (0) | 2023.02.16 |
|---|---|
| self.tableView.reloadData()가 Swift에서 작동하지 않음 (0) | 2023.02.16 |
| 사용자 정의 양식에서 Wordpress 데이터베이스 테이블에 데이터 삽입 (0) | 2023.02.16 |
| 클라이언트 알림, AJAX Push 또는 Poll을 사용해야 합니까? (0) | 2023.02.16 |
| Woocommerce 플러그인에서 "Ship to a Different Address?" 확인란 숨기기 또는 삭제 (0) | 2023.02.12 |