programing

twitter 부트스트랩 자동 검색 Ajax 예제

oldcodes 2023. 5. 9. 23:00
반응형

twitter 부트스트랩 자동 검색 Ajax 예제

저는 드롭다운을 채우기 위해 아약스 호출을 할 트위터 부트스트랩 자동 검색 요소의 작동 예를 찾고 있습니다.

Ajax URL과 응답 처리 방법을 정의하는 기존 작업 jquery 자동 완성 예제가 있습니다.

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    var options = { minChars:3, max:20 };
    $("#runnerquery").autocomplete('./index/runnerfilter/format/html',options).result(
            function(event, data, formatted)
                {
                    window.location = "./runner/index/id/"+data[1];
                }
            );
       ..

이것을 자동 검색 예제로 변환하려면 무엇을 변경해야 합니까?

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    var options = { source:'/index/runnerfilter/format/html', items:5 };
    $("#runnerquery").typeahead(options).result(
            function(event, data, formatted)
                {
                    window.location = "./runner/index/id/"+data[1];
                }
            );
       ..

자동 검색을 위한 원격 소스 지원 추가' 문제가 해결될 때까지 기다리겠습니다.

편집: 자동 검색 기능이 부트스트랩 3에 더 이상 번들되지 않습니다.체크아웃:

부트스트랩 2.1.0부터 2.3.2까지는 다음을 수행할 수 있습니다.

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('/typeahead', { query: query }, function (data) {
            return process(data.options);
        });
    }
});

다음과 같이 JSON 데이터를 사용하는 방법:

{
    "options": [
        "Option 1",
        "Option 2",
        "Option 3",
        "Option 4",
        "Option 5"
    ]
}

JSON 데이터는 올바른 MIME 유형(애플리케이션/json)이어야 하므로 jQuery는 JSON으로 인식합니다.

Ajax 호출을 지원하는 BS Typeahead 포크를 사용할 수 있습니다.그러면 다음과 같이 쓸 수 있습니다.

$('.typeahead').typeahead({
    source: function (typeahead, query) {
        return $.get('/typeahead', { query: query }, function (data) {
            return typeahead.process(data);
        });
    }
});

부트스트랩 2.1.0부터 시작:

HTML:

<input type='text' class='ajax-typeahead' data-link='your-json-link' />

Javascript:

$('.ajax-typeahead').typeahead({
    source: function(query, process) {
        return $.ajax({
            url: $(this)[0].$element[0].dataset.link,
            type: 'get',
            data: {query: query},
            dataType: 'json',
            success: function(json) {
                return typeof json.options == 'undefined' ? false : process(json.options);
            }
        });
    }
});

이제 HTML 코드에 "json-request" 링크를 배치하여 통합 코드를 만들 수 있습니다.

모든 응답은 BootStrap 3에 더 이상 없는 BootStrap 2 자동 검색을 참조합니다.

새로운 포스트 부트스트랩 Twitter typeahead.js를 사용하는 AJAX 예제를 찾는 다른 사람들을 위해, 여기 작업 예제가 있습니다.구문이 조금 다릅니다.

$('#mytextquery').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  limit: 12,
  async: true,
  source: function (query, processSync, processAsync) {
    processSync(['This suggestion appears immediately', 'This one too']);
    return $.ajax({
      url: "/ajax/myfilter.php", 
      type: 'GET',
      data: {query: query},
      dataType: 'json',
      success: function (json) {
        // in this example, json is simply an array of strings
        return processAsync(json);
      }
    });
  }
});

이 예제에서는 동기식(동기화 처리 호출) 및 비동기식 제안을 모두 사용하므로 일부 옵션이 즉시 나타나고 다른 옵션이 추가됩니다.둘 중 하나만 사용하시면 됩니다.

바인딩 가능한 이벤트와 문자열이 아닌 객체 작업을 포함한 매우 강력한 옵션이 있습니다. 이 경우 사용자 지정 표시 기능을 사용하여 항목을 텍스트로 렌더링할 수 있습니다.

오리지널 타이프어헤드 부트스트랩 플러그인에 아약스 기능을 추가했습니다.매우 사용하기 쉽습니다.

$("#ajax-typeahead").typeahead({
     ajax: "/path/to/source"
});

다음은 Github repo입니다.아약스-타입어헤드

jquery-ui.min.js에서 몇 가지 수정을 했습니다.

//Line 319 ORIG:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(...
// NEW:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...

// Line 328 ORIG:
this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
// NEW:this.element.attr....

// Line 329 ORIG:
this.active=a.eq(0).children("a")
this.active.children("a")
// NEW:
this.active=a.eq(0).addClass("active").children("a")
this.active.removeClass("active").children("a")`

그리고 다음의 css를 추가합니다.

.dropdown-menu {
    max-width: 920px;
}
.ui-menu-item {
    cursor: pointer;        
}

완벽하게 작동합니다.

부트스트랩을 이용해 전화를 걸 수 있습니다.현재 버전에는 소스 업데이트 문제가 없습니다. 사후 응답으로 부트스트랩의 자동 검색 데이터 소스를 업데이트하는 데 문제가 있습니다. 즉, 업데이트된 부트스트랩의 소스를 다시 수정할 수 있습니다.

예를 보려면 아래를 참조하십시오.

jQuery('#help').typeahead({
    source : function(query, process) {
        jQuery.ajax({
            url : "urltobefetched",
            type : 'GET',
            data : {
                "query" : query
            },
            dataType : 'json',
            success : function(json) {
                process(json);
            }
        });
    },
    minLength : 1,
});

이 방법을 사용하고 있습니다.

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},
    {
    name: 'options',
    displayKey: 'value',
    source: function (query, process) {
        return $.get('/weather/searchCity/?q=%QUERY', { query: query }, function (data) {
            var matches = [];
            $.each(data, function(i, str) {
                matches.push({ value: str });
            });
            return process(matches);

        },'json');
    }
});

서비스에서 올바른 응용 프로그램/json 컨텐츠 유형 헤더를 반환하지 않는 경우 이 방법을 사용해 보십시오.

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('/typeahead', { query: query }, function (data) {
            var json = JSON.parse(data); // string to json
            return process(json.options);
        });
    }
});

승인된 답변의 커피 스크립트 버전을 찾는 사람들에게:

$(".typeahead").typeahead source: (query, process) ->
  $.get "/typeahead",
    query: query
  , (data) ->
    process data.options

나는 이 게시물을 검토했고 모든 것이 제대로 작동하기를 원하지 않았고 결국 몇 개의 답변에서 나온 비트들을 함께 조각내어 100% 작업 데모를 가지고 있고 참조를 위해 여기에 붙여넣을 것입니다. 이것을 php 파일에 붙여넣고 포함물이 올바른 위치에 있는지 확인합니다.

<?php if (isset($_GET['typeahead'])){
    die(json_encode(array('options' => array('like','spike','dike','ikelalcdass'))));
}
?>
<link href="bootstrap.css" rel="stylesheet">
<input type="text" class='typeahead'>
<script src="jquery-1.10.2.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('index.php?typeahead', { query: query }, function (data) {
            return process(JSON.parse(data).options);
        });
    }
});
</script>

저는 당신을 위한 실용적인 예도 없고 아주 깨끗한 해결책도 없지만, 제가 발견한 것을 말씀드리겠습니다.

TypeAhead의 Javascript 코드를 보면 다음과 같습니다.

items = $.grep(this.source, function (item) {
    if (that.matcher(item)) return item
  })

이 코드는 jQuery "grep" 메서드를 사용하여 소스 배열의 요소를 일치시킵니다.AJAX 호출에서 연결할 수 있는 곳을 찾지 못했기 때문에 "깨끗한" 해결책이 없습니다.

그러나 이 작업을 수행할 수 있는 한 가지 방법은 jQuery에서 grep 메서드가 작동하는 방식을 활용하는 것입니다.grep의 첫 번째 인수는 소스 배열이고 두 번째 인수는 소스 배열을 일치시키는 데 사용되는 함수입니다(부트스트랩이 초기화할 때 제공한 "일치자"를 호출함).소스를 더미 단일 요소 배열로 설정하고 일치자를 AJAX 호출이 포함된 함수로 정의할 수 있습니다.그러면 소스 어레이에 요소가 하나만 있기 때문에 AJAX 호출이 한 번만 실행됩니다.

이 솔루션은 구식일 뿐만 아니라 TypeAhead 코드가 모든 키 누름판을 검색하도록 설계되었기 때문에 성능 문제가 발생합니다(AJAX 호출은 실제로는 몇 번의 키 입력마다 또는 일정 시간의 유휴 시간 후에만 발생해야 함).제 조언은 시도해 보는 것이지만, 다른 자동 완성 라이브러리를 사용하거나 문제가 발생할 경우 AJAX가 아닌 상황에서만 사용하는 것입니다.

업데이트: 이 포크를 사용하여 코드를 수정했습니다.

또한 각각 $.map을 사용하는 대신 토미슬라브 마르코프스키가 제안한 $.map로 변경했습니다.

$('#manufacturer').typeahead({
    source: function(typeahead, query){
        $.ajax({
            url: window.location.origin+"/bows/get_manufacturers.json",
            type: "POST",
            data: "",
            dataType: "JSON",
            async: false,
            success: function(results){
                var manufacturers = new Array;
                $.map(results.data.manufacturers, function(data, item){
                    var group;
                    group = {
                        manufacturer_id: data.Manufacturer.id,
                        manufacturer: data.Manufacturer.manufacturer
                    };
                    manufacturers.push(group);
                });
                typeahead.process(manufacturers);
            }
        });
    },
    property: 'name',
    items:11,
    onselect: function (obj) {

    }
});

하지만 저는 몇 가지 문제에 직면하고 있습니다.

Uncatched TypeError: 정의되지 않은 'toLowerCase' 메서드를 호출할 수 없습니다.

당신이 새로운 게시물에서 볼 수 있듯이, 나는 여기서 알아내려고 노력하고 있습니다.

이 업데이트가 당신에게 도움이 되기를 바랍니다...

나는 사용합니다.$().one()이 문제를 해결하기 위해; 페이지가 로드되면 서버에 Ajax를 보내고 완료되기를 기다립니다.그런 다음 결과를 함수에 전달합니다.$().one()중요합니다.typehead.js를 강제로 입력에 한 번 부착하기 때문입니다.글을 잘못 써서 죄송합니다.

(($) => {
    
    var substringMatcher = function(strs) {
        return function findMatches(q, cb) {
          var matches, substringRegex;
          // an array that will be populated with substring matches
          matches = [];
      
          // regex used to determine if a string contains the substring `q`
          substrRegex = new RegExp(q, 'i');
      
          // iterate through the pool of strings and for any string that
          // contains the substring `q`, add it to the `matches` array
          $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
              matches.push(str);
            }
          });
          cb(matches);
        };
      };
      
      var states = [];
      $.ajax({
          url: 'https://baconipsum.com/api/?type=meat-and-filler',
          type: 'get'
      }).done(function(data) {
        $('.typeahead').one().typeahead({
            hint: true,
            highlight: true,
            minLength: 1
          },
          {
            name: 'states',
            source: substringMatcher(data)
          });
      })
      

})(jQuery);
.tt-query, /* UPDATE: newer versions use tt-input instead of tt-query */
.tt-hint {
    width: 396px;
    height: 30px;
    padding: 8px 12px;
    font-size: 24px;
    line-height: 30px;
    border: 2px solid #ccc;
    border-radius: 8px;
    outline: none;
}

.tt-query { /* UPDATE: newer versions use tt-input instead of tt-query */
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}

.tt-hint {
    color: #999;
}

.tt-menu { /* UPDATE: newer versions use tt-menu instead of tt-dropdown-menu */
    width: 422px;
    margin-top: 12px;
    padding: 8px 0;
    background-color: #fff;
    border: 1px solid #ccc;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 8px;
    box-shadow: 0 5px 10px rgba(0,0,0,.2);
}

.tt-suggestion {
    padding: 3px 20px;
    font-size: 18px;
    line-height: 24px;
    cursor: pointer;
}

.tt-suggestion:hover {
    color: #f0f0f0;
    background-color: #0097cf;
}

.tt-suggestion p {
    margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

<input class="typeahead" type="text" placeholder="where ?">

Ajax를 사용할 때 시도합니다.$.getJSON()대신에$.get()결과를 올바르게 표시하는 데 문제가 있는 경우

제 경우에는 사용할 때 모든 결과의 첫 번째 문자만 받았습니다.$.get()사용하긴 했지만,json_encode()서버측의

 $('#runnerquery').typeahead({
        source: function (query, result) {
            $.ajax({
                url: "db.php",
                data: 'query=' + query,            
                dataType: "json",
                type: "POST",
                success: function (data) {
                    result($.map(data, function (item) {
                        return item;
                    }));
                }
            });
        },
        updater: function (item) {
        //selectedState = map[item].stateCode;

       // Here u can obtain the selected suggestion from the list


        alert(item);
            }

    }); 

 //Db.php file
<?php       
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'TableName');

$sql = $conn->prepare("SELECT * FROM TableName WHERE name LIKE ?");
$sql->bind_param("s",$search_param);            
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    $Resut[] = $row["name"];
    }
    echo json_encode($Result);
}
$conn->close();

?>

언급URL : https://stackoverflow.com/questions/9232748/twitter-bootstrap-typeahead-ajax-example

반응형