我正在尝试使用来自数据库的源使jquery自动完成输入字段,并且数据存储在json中。我将所有数据存储在一个变量中,如下所示:
,当我将source设置为该sinput字段的值时,我得到了整个句子(这是我的示例所期望的)。但是现在我知道了三个词(第一个-skijanje,第二个-vodopoad,第三个-更多),以便在我的自动填充中提供三个选项。这是我使用php获取数据的代码:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($output);
这是用于读取该数据的js代码:
<script>
var obj, dbParam, xmlhttp,x , txt = "";
var i = 0;
obj = { "table":"tourplan" };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "All data: " + this.responseText;
var myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x].title +" ";
}
document.getElementById("demo2").value = txt;
//document.getElementById("demo2").innerHTML = "Only one field: " + myObj[1].title;
}
}
xmlhttp.open("GET", "tourTitle.php?x=" + dbParam, true);
xmlhttp.send();
</script>
<p id="demo"></p>
<input type="text" id="demo2" value="">
对于document.getElementByID('demo').innerHTML = "All data: " + this.responseText;
,我得到了:
所有数据:[{“ title”:“ skijanje”,“ type”:“ zima”},{“ title”:“ vodopad”,“ type”:“ jesen-proljece-ljeto”},{“ title “:”更多“,”类型“:” ljeto“}]
这里是进行自动填充的步骤:
<script>
$( function() {
var otherPlaces = [
txt
];
$("#search-loged").autocomplete({
source: txt
});
});
</script>
对这个想法有想法吗?谢谢
答案 0 :(得分:0)
不要使用纯ajax,请尝试如下操作:
jQuery Ajax
$( function() {
$("#search-loged").autocomplete({
source: 'tourTitle.php',
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
});
HTML
<p id="demo"></p>
<input type="text" id="demo2" value="" name='x'>
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
$response = array();
foreach($output as row){
$response[] = ["value"=>$row['title'],"label"=>$row['title']];
}
echo json_encode($response);