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>

获取.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并找到了数据获取.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
      };
    }
  }
});

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

标记.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>

获取.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 的多个用户那里得到了帮助。感谢他们所有人。

但是,我仍在完善其他领域,例如在数据库中添加标签。完成后,我将发布完整的n个最终代码。