在第10行中,我为我插入了getSuggestion(q);
以从我的数据库中获取结果,但它不起作用。
为了让我从其他代码保持不变的同时从数据库中检索结果,我应该放在那里?
这是我目前的代码:
<html>
<script type="text/javascript" src="javascript/hogan-2.0.0.js"></script>
<script type="text/javascript" src="javascript/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="javascript/typeahead.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
getSuggestion(q);
});
});
</script>
<script type="text/javascript">
//document.getElementById("suggestion")
function getSuggestion(q) {
var ajax;
if(window.XMLHttpRequest)//for ie7+, FF, Chrome
ajax = new XMLHttpRequest();//ajax object
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
ajax.onreadystatechange = function() {
if(ajax.status === 200 && ajax.readyState === 4) {
//if result are not there then don't display them
if(ajax.responseText === "")
document.getElementById("suggestion").style.visibility = "hidden";
else {
document.getElementById("suggestion").style.visibility = "visible";
document.getElementById("suggestion").innerHTML = ajax.responseText;
}
}
};
ajax.open("GET", "suggestion.php?q=" + q, false);
ajax.send();
}
</script>
</html>
提前致谢。
答案 0 :(得分:1)
替换
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
getSuggestion(q);
});
});
</script>
用这个:
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
name: 'q',
remote: '/suggestion.php?q=%QUERY',
minLength: 3, // start searching if word is at least 3 letters long. Reduces database queries count
limit: 10 // show only first 10 results
});
});
</script>
这就是你所需要的。 Typeahead完成其余的工作。
查询位于$ _GET ['q']
中您可以找到我的示例here
我的 index.php 如下所示:
<html>
<head>
<link rel="stylesheet" href="http://twitter.github.io/typeahead.js/css/main.css">
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.9.3/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
name: 'q',
remote: '/typeahead/suggestion.php?q=%QUERY',
minLength: 3, // start searching if word is at least 3 letters long. Reduces database queries count
limit: 10 // show only first 10 results
});
});
</script>
</head>
<body>
<input type="text" class="q typeahead tt-query" />
</body>
您不需要输入css文件或类。只需要“q”类。
<input type="text" class="q" />
suggestion.php 来源:
<?php
$q = $_GET['q'];
echo json_encode(array($q));
?>
正如您所看到的,当您搜索时,它会以您键入的相同结果回答。您必须使用json_encode
创建数据库查询和回显数组请记住向远程参数添加正确的网址。
编辑:我的示例现在从itunes获取数据并搜索音乐视频。编辑的源代码可用。