我在本地机器上测试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,它运行正常.它正在返回数据.
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值.