【发布时间】:2018-03-07 17:23:39
【问题描述】:
拜托,我是 php 的初学者。 我想使用这样的 json 编码的数组: http://stegonia.fr/autocomplete/index2.php(你可以看到 var_dump 的结果)。 我希望能够以自动完成形式查看值和标签名称,并将 ID 号存储在我的数据库中。
我想使用这个自动完成解决方案:
http://stegonia.fr/autocomplete/index3.php
这个解决方案(index3)的javascript是:
<script>
$(document).ready(function () {
$('#speciesname').typeahead({
source: function (query, result) {
$.ajax({
url: "server3.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
});
server2的php代码是这个:
$term = trim(strip_tags($_GET['term']));
$a_json = array();
$a_json_row = array();
if ($data = $mysqli->query("SELECT * FROM `taxrefv11_mini` WHERE `GROUP2_INPN` = 'oiseaux' and `NOM_VERN` LIKE '%$term%' ORDER BY `NOM_VERN`")) {
while($row = mysqli_fetch_array($data)) {
$nomlat = htmlentities(stripslashes($row['NOM_VALIDE']));
$nomvern = htmlentities(stripslashes($row['NOM_VERN']));
$code = htmlentities(stripslashes($row['CD_REF']));
$a_json_row["id"] = $code;
$a_json_row["value"] = $nomvern.' '.$nomlat;
$a_json_row["label"] = $nomlat.' '.$nomvern;
array_push($a_json, $a_json_row);
}
}
// jQuery wants JSON data
echo json_encode($a_json);
flush();
$mysqli->close();
拜托,我不太了解javascript,我的问题是:
如果我使用 server2.php 发送的 json 文件,index3 的 javascript 获取“id”、“value”和“label”值的正确语法是什么?
谢谢 奥利维尔
【问题讨论】:
-
我看到的是您的 php 只返回名称。输入 "h" 返回 0:"Harle piette" 1: "h..." 必须将行推送到 $_a_json_row 然后像现在一样推送
-
谢谢 Luis Gar。事实上,我会在 index3 的脚本中使用 server2 的结果(链接到 index2)。但是我不知道如何在 index3 的这个脚本中获取 id、value 和 label ......这是我的问题。
-
现在您将拥有密钥,因此成功: function (data) { return data.id; }));
-
谢谢 luis,你的意思是新脚本是
$(document).ready(function () { $('#speciesname').typeahead({ source: function (query, result) { $.ajax({ url: "server3.php", data: 'query=' + query, dataType: "json", type: "POST", success: function (data) { return data.id; })); } }); } }); });它不能这样工作:(
标签: php json autocomplete