我正在尝试使用以下给定脚本从MySQL数据库自动完成数据。在开发人员工具网络中给出正确响应时,它没有显示标签。
JS
$('#search').autocomplete({
source: function( request, response ) {
$.ajax({
url: 'search.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'type'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: code['id'],
value: code['id'],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
$('#player').val(ui.item.data.player);
$('#marks').val(ui.item.data.marks);
}
});
search.php
$type = $_POST['type'];
$id = $_POST['name_startsWith'];
$query = $db->prepare("SELECT id, player, marks, note FROM players where ( id LIKE '".$id."%') ");
$query->execute();
$data = array();
$i = 0;
while ($row = $query->fetch(PDO:: FETCH_ASSOC)) {
$data[$i]['id'] = $row['id'];
$data[$i]['player'] = $row['player'];
$data[$i]['marks'] = $row['marks'];
++$i;
}
echo json_encode($data);
网络响应
[{"id":"4133","player":"Sam","marks":"65"},{"id":"4955","player":"valiu","marks":"34"}]
答案 0 :(得分:1)
替换此:
return {
label: code['id'],
value: code['id'],
data : item
}
使用:
return {
label: item['id'],
value: item['id'],
data : item
}
您传递了错误的参数。
还从小提琴中进行更新,然后进行测试
将网址更改为url: 'https://jqueryui.com/resources/demos/autocomplete/search.php?term=ro'
并将dataType更改为dataType: "jsonp"
然后测试