栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

jQuery select2:从php

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jQuery select2:从php

这就是答案。如何从数据库中获取数据。

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个最终代码。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383978.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号