2017-09-04 10 views
2

나는 Typeahead에서 초보자입니다. 이제 정적 방식에서 아약스 방식으로 타이프 헤드를 변경해야합니다. 코드는 같다,ajax 선행 사용법

var countries2 = [{ labelPost: "AUSTRALIAN NATIONAL UNIVERSITY ACT 200", valuePost: 200 }, 
 
    { labelPost: "DARWIN NT 800", valuePost: 800 }, { labelPost: "DARWIN NT 801", valuePost: 801 }, { labelPost: "WAGAIT BEACH NT 803", valuePost: 803 }, 
 
    { labelPost: "PARAP NT 804", valuePost: 804 }, { labelPost: "ALAWA NT 810", valuePost: 810 }, { labelPost: "BRINKIN NT 810", valuePost: 810 }, { labelPost: "CASUARINA NT 810", valuePost: 810 }]; 
 

 
$('#txtPostcode').typeahead({ 
 
       name: 'Postcode', 
 
       displayText: function (item) { return item.labelPost; }, 
 
       items: 10, 
 
       source: countries2, 
 
       updater: function (item) { 
 
        $('#txtPost').val(item.valuePost); 
 
        return item.labelPost; 
 
       } 
 
      });

그럼 출력은 A JSON 파일에 배열 "city.json" 내가 로컬 호스트를 열리는하여 방문 할 수있는 프로젝트 폴더에 넣어/city.json, 그런 다음 코드를 시도했습니다.

$('#txtPostcode').typeahead({ 
      name: 'Postcode', 
      displayText: function (item) { return item.city; }, 
      items: 10, 
      source: function (query, process) { 
       var parameter = { query: query }; 
       $.get('city.json', parameter, function (data) { 
        process(data); 
       }); 

작동하지 않으며 오류를 발생시키지 않았습니다.

그런 다음이 방법을 시도했습니다.

$('#txtPostcode').typeahead({ 
      name: 'Postcode', 
      displayText: function (item) { return item.labelPost; }, 
      items: 10, 
      source: { 
       ajax: { 
        url: "/city.json", 
       } 
      }, 
      updater: function (item) { 
       $('#txtPost').val(item.valuePost); 
       return item.labelPost; 
      } 
     }); 

그러나 같은 결과입니다.

누군가가 도와 줄 수 있습니까?

+0

당신이 개발자 도구의 네트워크 탭에서 확인 했습니까? 이것은 경로 문제로 보인다. – Manwal

+0

안녕하세요 Manwal, 개발 도구에서 콘솔을 확인했습니다. 오류가 발생하지 않았습니다. 네트워크 탭에 문제가없는 것 같습니다. 그리고 다른 사람에게 경로를 변경하면, 뭔가를 입력 할 때 바로 404 오류가 발생합니다. 내 생각 엔 그 파일에 도달 할 수 있다는 뜻입니다. – Rich

답변

1

BloodHound을 사용할 수 있습니다. Ajax 요청 안에 함수를 삽입해야합니다. 아래의 예를 작업 :

이 각각의 기능을 대체

var cities = []; 
var firstnames = []; 

$.ajax({ 
    url: "your.json", // load your Json 
    cache: false, 
    dataType: "json", 
    success: function(data) { 
    $.each(data, function(i, field){ // create a table with your data 
     cities.push(field); 
    }); 
    var firstcitynames = new Bloodhound({ // use Bloodhound for create maping of your data 
     datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"), 
     queryTokenizer: Bloodhound.tokenizers.whitespace, 
     local: $.map(cities, function(cityName) { return { value: cityName }; }), 
     limit:50 
    }); 

    firstcitynames.initialize(); 

    $("#scrollable-dropdown-menu .typeahead").typeahead({ 
     hint: false, 
     highlight: true, 
     minLength: 3 
    }, 
    { 
     name: "firstcitynames", 
     displayKey: "value", 
     source: firstcitynames.ttAdapter() 
    }).bind("typeahead:selected", function(obj, datum, name) { 
     // here action after select choice 
    }); 
    } 
}); 

UPDATE :

var cities = []; 
var firstnames = []; 

$.ajax({ 
    url: "http://vocab.nic.in/rest.php/country/json", 
    cache: false, 
    dataType: "json", 
    success: function (data) { 
    $.each(data.countries, function (i, field) { 
     cities.push(field.country.country_name); 
    }); 

    var firstcitynames = new Bloodhound({ // use Bloodhound for create maping of your data 
     datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"), 
     queryTokenizer: Bloodhound.tokenizers.whitespace, 
     local: $.map(cities, function (cityName) { return { value: cityName }; }), 
     limit: 50 
    }); 

    firstcitynames.initialize(); 

    $(".typeahead").typeahead({ 
     hint: false, 
     highlight: true, 
     minLength: 1 
    }, 
    { 
     name: "firstcitynames", 
     displayKey: "value", 
     source: firstcitynames.ttAdapter() 
    }).bind("typeahead:selected", function (obj, datum, name) { 
     // here action after select choice 
    }); 
    } 
}); 
+0

고마워, 프랭크. 내 코드를 변경하려고했습니다. – Rich

+0

고마워, 프랭크. url : url을 "path.json"으로 바꿨는데, json 파일의 위치는 http : // localhost : 58912/path.json과 같은 url로 직접 열 수 있지만 작동하지 않으며 오류가 발생하지 않습니다. . 그런 다음 "console.log (data)"를 "success : function (data) {"이 줄에 넣으면 전혀 호출되지 않는 것 같습니다. :-( – Rich

+0

그리고 여기에 넣었습니다. https://codepen.io/KunLi/pen/prBoXa?editors=1111 – Rich