13

Sto usando typstead Bootstrap con una funzione ajax e voglio sapere qual è il formato corretto del risultato Json, per restituire un ID e una descrizione. Ho bisogno dell'ID per associare l'elemento selezionato typeahead con un modello mvc3.Bootstrap typeahead ajax result format - Esempio

Questo è il codice:

[Html] 

    <input id="myTypeahead" class='ajax-typeahead' type="text" data-link="myUrl" data-provide="typeahead" /> 


    [Javascript] 

    $('#myTypeahead').typeahead({ 
     source: function (query, process) { 
      return $.ajax({ 
       url: $('#myTypeahead').data('link'), 
       type: 'post', 
       data: { query: query }, 
       dataType: 'json', 
       success: function (jsonResult) { 
        return typeof jsonResult == 'undefined' ? false : process(jsonResult); 
       } 
      }); 
     } 
    }); 



This works properly when I return a simple list of strings, for example: 
{item1, item2, item3} 

But I want to return a list with Id, for example: 
{ 
{Id: 1, value: item1}, 
{Id: 2, value: item2}, 
{Id: 3, value: item3} 
} 

Come elaborare questo risultato nella Ajax "successo: function()"?

Questo è molto facile con jquery Completamento automatico, perché posso restituire un elenco di oggetti JSON.

[jquery Autocomplete process data example] 
...    
success: function (data) { 
       response($.map(data, function (item) { 
        return { label: item.Id, value: item.Value, id: item.Id, data: item }; 
       }) 
... 

Ma questo non funziona con boostrap Typeahead.

Qualcuno può aiutarmi?

Grazie.

+0

Avete provato a convertire i valori di ritorno come un 'array? 'var list = [{Id: 1, value: item1}, {Id: 2, value: item2}, {Id: 3, value: item3}];' –

+0

sì, non ho alcun problema. Il mio problema è come associare l'Id con il controllo html. La funzione di processo (dati) accetta solo un array di stringhe, non un array di oggetti – Gonzalo

+0

Si sta utilizzando l'ultima versione di TypeAhead? –

risposta

40

Ci provo per due giorni e finalmente riesco a farlo funzionare. Bootstrap Typeahead non supporta una matrice di oggetti come risultato di default, solo una serie di stringhe. Poiché le funzioni "matcher", "sorter", "updater" e "evidenziatore" prevedono le stringhe come parametri.

Invece, "Bootstrap" supporta le funzioni personalizzabili "matcher", "sorter", "updater" e "evidenziatore". Quindi possiamo riscrivere quelle funzioni nelle opzioni di Typeahead.

II ha usato il formato Json e ha associato l'ID a un input html nascosto.

Il codice:

$('#myTypeahead').typeahead({ 
    source: function (query, process) { 
     return $.ajax({ 
      url: $('#myTypeahead').data('link'), 
      type: 'post', 
      data: { query: query }, 
      dataType: 'json', 
      success: function (result) { 

       var resultList = result.map(function (item) { 
        var aItem = { id: item.Id, name: item.Name }; 
        return JSON.stringify(aItem); 
       }); 

       return process(resultList); 

      } 
     }); 
    }, 

matcher: function (obj) { 
     var item = JSON.parse(obj); 
     return ~item.name.toLowerCase().indexOf(this.query.toLowerCase()) 
    }, 

    sorter: function (items) {   
     var beginswith = [], caseSensitive = [], caseInsensitive = [], item; 
     while (aItem = items.shift()) { 
      var item = JSON.parse(aItem); 
      if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item)); 
      else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item)); 
      else caseInsensitive.push(JSON.stringify(item)); 
     } 

     return beginswith.concat(caseSensitive, caseInsensitive) 

    }, 


    highlighter: function (obj) { 
     var item = JSON.parse(obj); 
     var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') 
     return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { 
      return '<strong>' + match + '</strong>' 
     }) 
    }, 

    updater: function (obj) { 
     var item = JSON.parse(obj); 
     $('#IdControl').attr('value', item.id); 
     return item.name; 
    } 
}); 
+0

Grazie! Funziona come un fascino! –

+7

È ancora il modo migliore per eseguire questa attività? – EralpB

+0

Grazie, grazie! Amico, ho cercato ovunque una soluzione praticabile per ottenere il metodo typeahead bootstrap 2.3.2 per leggere un set di dati e aggiornare diversi campi sulla pagina in base all'elemento selezionato. In caso ho dimenticato di dirlo - grazie! – MichaelJTaylor

1

Nota: ho visto @ EralpB`s comment "Questo è ancora il modo migliore per realizzare questo compito?"

Sì, soluzione @Gonzalo funziona, ma sembra strano (come stampella, soprattutto dopo aver usato jQuery-Autocomplete) - dovrebbe funzionare "dalla scatola" .Better è quello di utilizzare questo - Bootstrap-3-Typeahead. Esso supporta un array di oggetti come risultato: format - [{id : .., nome: ...}, ..., {id : .., nome: ... }]. Esempio per il problema dell'OP:

.... 
source: function (query, process) { 
    return $.ajax({ 
     ...... 
     success: function (result) {    
      var resultList = []; 

      $.map(result,function (Id,value) { 
       var aItem = { id: Id, name: value}; 
       resultList.push(aItem); 
      }); 

      return process(resultList); 
     } 
    }); 
    }, 
Problemi correlati