【问题标题】:How to get jQuery autocomplete with PHP + MySQL Ajax and pass to JavaScript如何使用 PHP + MySQL Ajax 获取 jQuery 自动完成并传递给 JavaScript
【发布时间】:2012-08-26 03:02:12
【问题描述】:

我有一个用于自动完成搜索功能的 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();
        });
    });

});

【问题讨论】:

  • 您使用的是哪个自动完成插件?我可以看到您使用的是 jquery,您可能需要查看 $.post 方法。
  • 我认为它是 jQuery UI 的,但它看起来像是 devbridge.com/projects/autocomplete/jquery
  • @PezCuckow 是的,它基于 devbridge 自动完成功能。

标签: php javascript mysql ajax jquery


【解决方案1】:

基于这个自动完成插件http://www.devbridge.com/projects/autocomplete/jquery/

您的 JavasSript 需要如下所示:

//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);

插件需要像下面这个 PHP 应该提供的 json

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

【讨论】:

  • 我尝试了您的建议,但现在显示任何结果。但是当我手动尝试 search.php?term=countryname 它确实显示结果。
  • 那么你的PHP有问题,检查语法错误。您是否已将脚本连接到您的数据库?
  • 嗨,是的,当我手动尝试 php 脚本时,我能够获得结果示例:localhost/search.php?query=li 然后我得到了结果列表,但在自动完成搜索输入中它没有显示任何内容。
  • 嗨佩斯,非常感谢。问题出在 PHP 脚本上,插件需要您提供的格式。谢谢。
【解决方案2】:

针对 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

【讨论】:

  • +1,Pez 关于输出格式的回答不起作用,但这对我有用。用于 jQuery 的 Ajax 自动完成功能,版本 1.2.7
【解决方案3】:

不要使用您使用过的插件,而是使用以下链接中提供的插件:

Jquery UI Autocomplete

使用此插件,您可以使用 php 访问数据库中的数据。它肯定会起作用。

【讨论】:

    【解决方案4】:

    由于您已经在使用 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 中尝试 autocomplete。虽然不太确定浏览器支持。但这里有一个例子:

    <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/

    【讨论】:

    • 自动完成插件内置了这个?
    猜你喜欢
    • 1970-01-01
    • 2020-12-28
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多