我想使用 this jquery plugin从数据库中获取值...
我创建 jquery ajax 代码和 HTML 以从数据库中获取值:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<link href="http://ivaynberg.github.com/select2/select2-3.3.2/select2.css" rel="stylesheet" type="text/css" />
<script src="http://ivaynberg.github.com/select2/select2-3.3.2/select2.js"></script>
</head>
<body>
<select id="test" style="width:200px;">
<option value=""><option>
</select>
<script>
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
}
});
</script>
</body>
和json.php代码:
<?php
$pdo=new PDO("mysql:dbname=ddd;host=localhost","ddd","ddd");
$statement=$pdo->prepare("SELECT id,ime_prezime FROM radnici");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
当我运行 php 代码时,我得到 json:
[{"id":"1","ime_prezime":"Pera Peric"}]
问题不在于 php 代码...我的 html/jquery 代码有什么问题?
我没有得到任何东西,我无法从 json.php 文件中获取值
更新:
我发现错误是 json 格式,但现在我无法保存我得到的值,所以当我单击值时,值就消失了......
<input id="test" style="width:300px;">
<select multiple id="test" style="width:300px"></select>
<script>
function formatValues(data) {
return data.ime_prezime;
}
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
},
formatResult: formatValues
});
</script>
最佳答案
您需要返回id
, text
对并使用以下结构;
<input type="hidden" name="test" id="test" style="width:200px;"/>
$('#test').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
}
});
你可以在这里看到演示: http://jsfiddle.net/huseyinbabal/68fD2/1/ 。在演示中,我使用了本地数据,但它可以像上面那样与您的 ajax 代码一起使用。
编辑:
如果你想像在你的演示中那样做,你可以使用以下;
function formatValues(data) {
return data.ime_prezime;
}
var test = $('#test');
var data = [{"id":"1","ime_prezime":"Pera Peric"},
{"id":"2","ime_prezime":"Something else"},
{"id":"3","ime_prezime":"Lorem"},
{"id":"4","ime_prezime":"Ipsum"}
];
$(test).select2({
data:{results: data, text: 'ime_prezime'},
width: "300px",
formatResult: formatValues,
formatSelection: formatValues,
multiple: true
});
关于javascript - 使用 mysql 数据库中的值选择输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22388991/