2017-02-15 2 views
0

나는 Laravel 5.3에 트위터 타입 어 헤드를 사용하고 있습니다. , 제안 드롭 다운의 데이터를 원격 소스 JSON 배열은 JS 객체 배열에 매핑됩니다미리보기에서이 개체에 액세스하려면 어떻게해야합니까?

[ 
    { 
    "id": 2, 
    "name": "iphone", 
    "created_at": "2017-02-08 06:12:34", 
    "updated_at": "2017-02-08 06:12:34", 
    "user_id": 1, 
    "brand_id": 1, 
    "msds_url": "google.com", 
    "gravity": 1.03, 
    "recipe_id": null, 
    "relevance": 210, 
    "brand": { 
     "id": 1, 
     "name": "apple", 
     "created_at": "2017-02-08 03:00:49", 
     "updated_at": "2017-02-08 03:00:49", 
     "user_id": 1, 
     "abbreviation": "AP", 
     "visible": 1 
    } 
    } 
] 

value라고 : 그냥 알다시피, 여기 내 데이터는 제품의 및 제조업체 브랜드 (FK)와 함께 예를 들어 작성된 방식으로 형식이 지정됩니다. '애플 아이폰'.

var engine = new Bloodhound({ 
    datumTokenizer: function(datum) { 
    return Bloodhound.tokenizers.whitespace(datum.value); 
    }, 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    remote: { 
    wildcard: '%QUERY', 
    url: '/find?q=%QUERY%', 
    transform: function(response) { 
    console.log(response); 
     // Map the remote source JSON array to a JavaScript object array 
     return $.map(response, function(product) { 
     return { 
      value: product.brand.name+' - '+product.name, 
      other: product 
     }; 
     }); 
    } 
    } 
}); 

// Instantiate the Typeahead UI 
$('#search').typeahead(null,{ 
    display: 'value',//choose a key from the map 
    highlight: true, 
    hint: true, 
    source: engine 
}); 
나는 또한 brand.id 어떤 일을 할 것 캐스팅하고 싶은 무엇

, 일부 데이터가 동일한 입력에 속성으로, 2 될 것 product.id, 그래서 이벤트를 캡처하고 '선택된 제안을 기록 '라고 말합니다.

$("#search").on("typeahead:select", function(ev, suggestion) { 
    console.log(suggestion); 
}); 

문제는이

// Map the remote source JSON array to a JavaScript object array 
      return $.map(response, function(product) { 
      return { 
       value: product.brand.name+' - '+product.name, //this format 
       other: product //full access to object 
      }; 
      }); 

그래서 내가 otherdisplay 전환 블러드 하운드 부분에서지도 함수 내에서 특별히 포맷 있기 때문에 그것은 나에게 데이터의 전체 배열에 대한 액세스 권한을 부여하지 않는다는 것입니다 value 대신 브랜드 이름 및 제품 이름 대신 전체 개체가 전달되도록하십시오. 제안 드롭 다운에 올 때 내가 전에 달리 아직 액세스되지 않았기 때문에

$('#search').typeahead(null,{ 
    //display: 'value', 
    display: 'other', 
    highlight: true, 
    hint: true, 
    source: engine 
}); 

지금, 그것은 [object object]을 말할 것이다.

개체에 액세스하여 형식을 올바르게 지정하고 브랜드 ID 및 제품 ID에 대한 액세스를 유지하려면 어떻게해야합니까? 이렇게하면 나중에 양식을 제출할 때 선택한 제품 ID를 제품 테이블 항목과 일치시킬 수 있습니다.

답변

0

코드는 확인하지 않았지만 프로젝트에서이 코드를 사용하고 있습니다. 사용해보기 :

var engine = new Bloodhound({ 
    datumTokenizer: function(datum) { 
     var result = Bloodhound.tokenizers.whitespace(datum.name); 
     if (datum.brand != null){ 
      result = result.concat(Bloodhound.tokenizers.whitespace(datum.brand.name)); 
     } 
     return result; 
    }, 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    remote: { 
     wildcard: '%QUERY', 
     url: '/find?q=%QUERY%', 
     prepare: function(query, settings) { 
      settings.type = "GET"; 
      settings.dataType = "json" 
      settings.url = settings.url.replace('%QUERY', encodeURIComponent(query)); 
      return settings; 
     } 
    } 
}); 

engine.initialize(); 

$("#search").typeahead(null, { 
    name: 'engine', 
    displayKey: function(data){ 
     return data.name + (data.brand ? " - " + data.brand.name : ""); 
    }, 
    source: engine.ttAdapter(), 
}) 
.on('typeahead:selected', function($e, datum){ 
    //You may access the value object here 
    console.log("datum" ,datum); 
}); 

작동하는 경우 알려주십시오.

+0

완벽하게 작동합니다! 코드에 몇 가지 설명을 추가하십시오. 의심 할 여지없이 다른 사람들이 조금씩 어떻게 작동하는지 이해하고 싶을 것입니다. – ProEvilz

+0

그럼 대답을 받아 들일 수 있습니다. – ProEvilz

+0

3-4 년 전에 구현했습니다. 그 이후로이 코드를 변경 한 적이 없으며 문서를 살펴본 적이 없지만 문제는 발견하지 못했습니다. 귀하의 코드, 나는 문제가 거기에 데이터와''소스 : 엔진''진술을 조작지도 기능에 있다고 생각합니다. – Dev

관련 문제