jquery select2:从 php-mysql 获取数据时出错

jquery select2: error in getting data from php-mysql

我正在本地机器上测试 select2 插件。 但出于某种原因。它没有从数据库中收集数据。

我试了很多次都没有找到问题所在。

下面是代码。

<div class="form-group">

   <div class="col-sm-6">
       <input type="hidden" id="tags" style="width: 300px"/>
   </div>
</div> 

<script type="text/javascript">
var lastResults = [];

$("#tags").select2({
    multiple: 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",
        type: "POST",
      data: function (params) {
            return {
                q: params.term // search term
            };
            },
        results: function (data) {
            lastResults = data;
            return data;
        }
    },
    createSearchChoice: function (term) {
        var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
        return { id: term, text: text };
    },
});

$('#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);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},    
                   error: function () {
                      alert("error");
                   }
                });
               */
           } 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

我检查了 fetch.php,它工作正常。它正在返回数据。

<?php 
    require('db.php');

    $search = strip_tags(trim($_GET['q'])); 
    $query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");

    $query->execute(array(':search'=>"%".$search."%"));

    $list = $query->fetchall(PDO::FETCH_ASSOC);

    if(count($list) > 0){
       foreach ($list as $key => $value) {
        $data[] = array('id' => $value['tid'], 'text' => $value['tag']);                
       } 
    } else {
       $data[] = array('id' => '0', 'text' => 'No Products Found');
    }

    echo json_encode($data);

    ?>

我正在尝试创建标签,它将检查数据库中的标签。 如果找不到标签,则用户可以创建新标签,它将保存在数据库中并显示在用户用户选择中。

目前我还没有创建用于将标签保存在数据库中的页面。 我也尝试使用 select2 版本 3.5 和 4.0.1

这是我第一次尝试 select2 插件。所以,如果我犯了愚蠢的错误,请忽略。对此我深表歉意。

感谢您的宝贵时间。

编辑:

我检查了 firebug,发现数据 fetch.php 没有从输入框中获取任何值。它看起来像 Ajax 中的问题。因为它没有发送 q 值。

select2 v4+ 的配置不同于 v3.5+

它适用于 select2 v4:

HTML

<div class="form-group">
   <div class="col-sm-6">
    <select class="tags-select form-control" multiple="multiple" style="width: 200px;">
    </select>
  </div>
</div>

JS

$(".tags-select").select2({
  tags: true,
  ajax: {
    url: "fetch.php",
    processResults: function (data, page) {
      return {
        results: data
      };
    }
  }
});

答案在这里。如何从数据库中获取数据。

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);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},    
                   error: function () {
                      alert("error");
                   }
                });
               */
           } 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 result
if(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 json
echo json_encode($data);

?>

通过上面的代码,我可以从数据库中获取数据。我从 SO 获得了多个用户的帮助。感谢他们所有人。

但是,我仍在改进其他方面,例如在数据库中添加标签。一旦完成,我将 post 完成 n 个最终代码。