我试图制作一个可以从数据库中提取数据的脚本。我有以下代码,但它不适合我
<?php
$connection = new mysqli("localhost", "username", "password", "movies");
if($connection->error) {
die("I couldn't make the database connection");
}
$data = $connection->query("SELECT `id`, `title` FROM `titles`");
if($data->num_rows > 0) {
$results = array();
while($rows = $data->fetch_assoc()) {
$results[] = array($rows["id"], $rows["title"]);
}
}
header("Content-Type: application/json");
echo json_encode($results);
?>
使用以下HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete functionality</title>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#autocomplete1" ).autocomplete({
source:"data.php",
select: function( event, ui ) {
$( "#autocomplete1" ).val( ui.item.code + " - " + ui.item.label );
return false;
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.code + " - " + item.label + "</a>" )
.appendTo( ul );
};
});
</script>
</head>
<body>
<input type="text" id="autocomplete1">
</body>
</html>
然而,当我点击文本框时,我只得到一个空盒子,当我点击其中的某些内容时,我只是得到“未定义 - 未定义”出现在框中,当我应该从数据库中取回行< / p>
答案 0 :(得分:0)
你对我的mySQL查询很奇怪。试试这个。还可以使用var_dump()查看您是否从查询中获取了任何内容。从顶部开始,向下工作。在你真正在firebug中看到DOM错误之前,它不是JS问题。
<?php
$query = mysql_query("SELECT * from schema.table_name ") or die(mysql_error());
}
$results= array();
while($field = mysql_fetch_assoc($query)){
//set variables here or in your case insert values into array..
$id = $field['id'];
$title = $field['titles'];
$results[] = $title;
}//close while loop
var_dump($restults); //lest see if anything even comes back.
die;// i always die after this because who cares about the below until the above works.
?>
答案 1 :(得分:0)
首先尝试这个:
$( document ).ready(function() {
$( "#autocomplete1" ).autocomplete({
source:"data.php",
select: function( event, ui ) {
$( "#autocomplete1" ).val( ui.item.code + " - " + ui.item.label );
return false;
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.code + " - " + item.label + "</a>" )
.appendTo( ul );
};
});
或将您的脚本移到<input type="text" id="autocomplete1">
答案 2 :(得分:0)
$(function () {
$("#autocomplete1").autocomplete({
source: "data.php",
select: function (event, ui) {
$("#autocomplete1").val(ui.item.id+ " - " + ui.item.title);
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.id+ " - " + item.title+ "</a>")
.appendTo(ul);
};
});
如果$ results数组以格式results = [{id:'',title:''}]存储数据,则上面的代码应该可以完成这项工作。