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

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

我尝试了多次,但无法找到问题。

以下是代码。

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); } } } } });

fetch.php

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

 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

 

JS

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

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

tag.php

  

fetch.php

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

但是,我仍在改进其他领域,比如在数据库中添加标签。 一旦完成,我将发布完整的最终代码。