Dit is het voorbeeld:
HTML:
<input type="hidden" class="bigdrop" id="e6" style="width:600px" value="16340"/>
[js]
$("#e6").select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
initSelection: function(element, callback) {
// the input tag has a value attribute preloaded that points to a preselected movie's id
// this function resolves that id attribute to an object that select2 can render
// using its formatResult renderer - that way the movie name is shown preselected
var id=$(element).val();
if (id!=="") {
$.ajax("http://api.rottentomatoes.com/api/public/v1.0/movies/"+id+".json", {
data: {
apikey: "ju6z9mjyajq2djue3gbvv26t"
},
dataType: "jsonp"
}).done(function(data) { callback(data); });
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});[/js]
Daarvan heb je eerst maar een paar dingen nodig, een HTML element met een id:
HTML:
<input type="hidden" id="search" value=""/>
De initialisatie van de plugin (er vanuit gaande dat je die al hebt ingeladen via <script>):
[js]
$("#search").select2({
placeholder: "Zoeken",
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "",
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10 // Kun je later gebruiken
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
console.log(data);
}
}
});[/js]
Nu zijn er een aantal zaken die je moet wijzigen, met name het AJAX gedeelte.
De URL moet verwijzen naar het PHP script waarop je de zoekactie uit gaat voeren, vervolgens geef je met "data" aan wat er naar je script gestuurd wordt en bij "results" krijg je de reactie van het script terug.
Ik neem aan dat je bekend bent met PHP dus een database verbinding opzetten en een query uit laten voeren moet geen probleem zijn, de zoekterm die je vanuit deze plugin kunt gebruiken is binnen je script te benaderen via $_GET['q']