我有一个javascript代码,用于我的自动完成搜索功能,它运行良好。但如果你看下面的代码,搜索功能返回的数据是硬编码的,我想使用PHP从MySQL获取数据。
任何人都可以帮助我如何将下面的代码转换为使用PHP查询来收集数据MySQL,然后使用结果并将其传递给javascript?非常感谢。
//<![CDATA[
var a1;
var a2;
function InitMonths() {
a2.setOptions({ lookup: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(',') });
}
function InitWeekdays() {
a2.setOptions({ lookup: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(',') });
}
jQuery(function () {
a1 = $('#query').autocomplete({
width: 448,
delimiter: /(,|;)s*/,
lookup: 'Andorra,Azerbaijan,Bahamas,Bahrain,Bangladesh,Barbados,Belarus,Belgium,Belize,Benin,Bhutan,Bolivia,Bosnia Herzegovina,Botswana,Brazil,Brunei,Bulgaria,Burkina,etc'.split(',')
});
a2 = $('#months').autocomplete({
width: 448,
delimiter: /(,|;)s*/,
lookup: 'January,February,March,April,May,etc'.split(',')
});
$('#navigation a').each(function () {
$(this).click(function (e) {
var element = $(this).attr('href');
$('html').animate({ scrollTop: $(element).offset().top }, 300, null, function () { document.location = element; });
e.preventDefault();
});
});
});
新建
基于此自动完成插件http://www.devbridge.com/projects/autocomplete/jquery/
您的JavasScript需要看起来像:
//Start auto complete
a1 = $("#query").autocomplete({
serviceUrl:'search.php', //tell the script where to send requests
width: 448, //set width
//callback just to show it's working
onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); }
});
您的PHP(search.PHP)需要是:
///
/*** connect to your DB here ***/
///
//retrieve the search term and strip and clean input
$term = trim(strip_tags($_GET['query']));
//try to make user input safer
$term = mysqli_real_escape_string($term);
//build a query on the database
$qstring = "SELECT description as value,id FROM test WHERE description LIKE '%".$term."%'";
//query the database for entries containing the term
$result = mysql_query($qstring);
//array to return
$reply = array();
$reply['query'] = $term;
$reply['suggestions'] = array();
$reply['data'] = array();
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
//Add this row to the reply
$reply['suggestions'][]=htmlentities(stripslashes($row['value']));
$reply['data'][]=(int)$row['id'];
}
//format the array into json data
echo json_encode($reply);
插件期望json像下面这样,这个PHP应该提供
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
注意,我还没有测试过,但应该没问题
旧答案
请参见此处:http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/
首先,如果您没有使用jQuery自动完成插件(jQuery作为jQuery UI的一部分支持的插件),请设置它。http://jqueryui.com/demos/autocomplete/#remote
你在问如何彻底重新设计系统。
首先,您需要使用Ajax通过PHP作为代理将匹配字符串发送到数据库,然后PHP需要返回结果并让Javascript读取结果。
因此,您需要使用(作为配置):
a1 = $("#query").autocomplete({
source: "search.php"
width: 448
});
还有一些类似(作为你的PHP)的东西
//connect to your database
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT description as value,id FROM test WHERE description LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=(int)$row['id'];
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
针对Pez上面的回答,建议的PHP数组结构对我不起作用。我不得不这样构建我的数组:
$reply = array();
$reply['query'] = $term;
$reply['suggestions'] = array();
foreach ($items as $item) {
$reply['suggestions'][] = array('value' => htmlentities(stripslashes($item['value'])), 'data' => $item['id');
}
然后
return json_encode($reply);
我使用的是这里可用的库的v1.2.7版本:https://github.com/devbridge/jQuery-Autocomplete
不要使用您使用过的插件,而是使用以下链接上的插件:
Jquery UI自动完成
使用这个插件,您可以使用php访问数据库中的数据。它肯定会起作用。
由于您已经在使用jQuery插件,我假设您了解jQuery。在下面的代码中,我使用了一个名为$.post
的jQuery方法,该方法用于从服务器加载数据,而无需重新加载页面(您可以称之为ajax)
$.post('yourphp.php', function(data){
var obj = JSON.parse(data);
$('#months').autocomplete({
width: 448,
delimiter: /(,|;)s*/,
lookup: obj
});
});
在您的php:上
<?php
$months = ['jan', 'feb'...'dec'];
echo json_encode($months);
?>
我真的不知道你在用什么jQuery插件进行自动建议。但您可能想尝试从jquery ui或html5中的datalist自动完成。但对浏览器的支持还不太确定。但这里有一个例子:
<datalist id="yo_list">
<?php foreach(){ //loop through the result of your query here ?>
<option value="<?php echo $somevalue; ?>"><?php echo $somevalue; ?></option>
<?php } ?>
</datalist>
-没有真正测试代码,所以如果它不起作用或者有什么你不理解的地方,请告诉我。如果您想了解更多信息,这里有一个指向$.post
方法的链接:http://api.jquery.com/jQuery.post/