这就是答案。如何从数据库中获取数据。
tag.php
<script type="text/javascript">var lastResults = [];$("#tags").select2({ multiple: true, //tags: true, placeholder: "Please enter tags", tokenSeparators: [","], initSelection : function (element, callback) { var data = []; $(element.val().split(",")).each(function () { data.push({id: this, text: this}); }); callback(data); }, ajax: { multiple: true, url: "fetch.php", dataType: "json", delay: 250, type: "POST", data: function(term,page) { return {q: term}; //json: JSON.stringify(), }, results: function(data,page) { return {results: data}; }, }, minimumInputLength: 2, // max tags is 3 maximumSelectionSize: 3, createSearchChoice: function (term) { var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)"); // return { id: term, text: text }; return { id: $.trim(term), text: $.trim(term) + ' (new tag)' }; },});$('#tags').on("change", function(e){ if (e.added) { if (/ (new)$/.test(e.added.text)) {var response = confirm("Do you want to add the new tag "+e.added.id+"?");if (response == true) { alert("Will now send new tag to server: " + e.added.id); } else { console.log("Removing the tag"); var selectedTags = $("#tags").select2("val"); var index = selectedTags.indexOf(e.added.id); selectedTags.splice(index,1); if (selectedTags.length == 0) { $("#tags").select2("val",""); } else { $("#tags").select2("val",selectedTags); }} } }});</script>fetch.php
<?php // connect to database require('db.php');// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial $search = strip_tags(trim($_POST['term']));// Do Prepared Query $query = $mysqli->prepare("SELECT tid,tag FROM tag WHERe tag LIKE :search LIMIT 4");// Add a wildcard search to the search variable$query->execute(array(':search'=>"%".$search."%"));// Do a quick fetchall on the results$list = $query->fetchall(PDO::FETCH_ASSOC);// Make sure we have a resultif(count($list) > 0){ foreach ($list as $key => $value) { $data[] = array('id' => $value['tag'], 'text' => $value['tag']); } } else { $data[] = array('id' => '0', 'text' => 'No Products Found');}// return the result in jsonecho json_enpre($data);?>通过上面的代码,我能够从数据库中获取数据。我从SO的多个用户那里得到帮助。感谢所有人。
但是,我仍在完善其他领域,例如在数据库中添加标签。完成后,我将发布完整的n个最终代码。



