如何使用 PHP + MySQL Ajax 获取 jQuery 自动完成并传递给 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12212887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:36:16  来源:igfitidea点击:

How to get jQuery autocomplete with PHP + MySQL Ajax and pass to JavaScript

phpjavascriptmysqlajaxjquery

提问by webdev.gk

I have a javascript code that I am using for my autocomplete search feature and it is working fine. But if you look at the code below, the data that the search feature is returning is hard coded and I want to get the data from MySQL using PHP.

我有一个用于自动完成搜索功能的 javascript 代码,它运行良好。但是如果你看看下面的代码,搜索功能返回的数据是硬编码的,我想使用 PHP 从 MySQL 获取数据。

Anyone can help me how to convert the code below to use PHP query to gather data MySQL then use the results and pass it to javascript? Thank you.

任何人都可以帮助我如何将下面的代码转换为使用 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();
        });
    });

});

回答by Pez Cuckow

New

新的

Based on this auto complete plugin http://www.devbridge.com/projects/autocomplete/jquery/

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

Your JavasSript will need to look something like:

您的 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); } 
});

And your PHP (search.php) will need to be:

你的 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);

The plugin expects json like the below which this PHP should provide

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

query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']

Note I haven't tested this but it should be fine!

注意我没有测试过这个,但应该没问题!



Old Answer

旧答案

See here: http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/

见这里:http: //www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/

First of all if you're not using the jQuery autocomplete plugin (the one supported by jQuery as part of jQuery UI) set that up. http://jqueryui.com/demos/autocomplete/#remote

首先,如果您没有使用 jQuery 自动完成插件(jQuery 支持作为 jQuery UI 的一部分的插件),请进行设置。http://jqueryui.com/demos/autocomplete/#remote

You're asking how to completely rework the system.

你问的是如何彻底改造系统。

For a start you'll need to use Ajax to send the match string to the database via PHP as a proxy, then PHP will need to return the results and have the Javascript read them.

首先,您需要使用 Ajax 作为代理通过 PHP 将匹配字符串发送到数据库,然后 PHP 将需要返回结果并让 Javascript 读取它们。

So you'll need to use (as the config):

所以你需要使用(作为配置):

a1 = $("#query").autocomplete({
source: "search.php"
width: 448  
});

And something like (as your PHP)

和类似的东西(作为你的 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

回答by craigh

in response to Pez's answer above, the suggested PHP array structure did not work for me. I had to structure my array like so:

针对上面 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');
    }

then

然后

return json_encode($reply);

I am using v1.2.7 of the library available here: https://github.com/devbridge/jQuery-Autocomplete

我正在使用这里可用的库的 v1.2.7:https: //github.com/devbridge/jQuery-Autocomplete

回答by Shantanu Nirale

Instead of using the plugin you have used, use the plugin available on following link :

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

Jquery UI Autocomplete

Jquery UI 自动完成

Using this plugin you can get access to the data from database using php. It will work surely.

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

回答by Wern Ancheta

Since you're already using a jQuery plugin I assume that you know jQuery. In the code below I'm using a jQuery method called $.postwhich is used to load data from the server without reloading the page(ajax as you might call it)

由于您已经在使用 jQuery 插件,因此我假设您了解 jQuery。在下面的代码中,我使用了一个名为 jQuery 的方法$.post,该方法用于从服务器加载数据而无需重新加载页面(如您所称的 ajax)

$.post('yourphp.php', function(data){
     var obj = JSON.parse(data);
      $('#months').autocomplete({
                width: 448,
                delimiter: /(,|;)\s*/,
                lookup: obj
            });
}); 

On your php:

在你的 php 上:

<?php
$months = ['jan', 'feb'...'dec'];
echo json_encode($months);
?>

I don't really know what jQuery plugin you're using for the autosuggest. But you might want to try autocompletefrom jquery ui or datalist in html5. Not really sure about the browser support though. But here's an example:

我真的不知道您用于自动建议的 jQuery 插件。但是您可能想尝试从 html5 中的 jquery ui 或 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>

-Didn't really test the code, so let me know if it doesn't work or there's something you don't understand. Here's a link to the $.postmethod if you want to learn more: http://api.jquery.com/jQuery.post/

- 没有真正测试代码,所以如果它不起作用或有什么你不明白的地方,请告诉我。$.post如果您想了解更多信息,请访问该方法的链接:http: //api.jquery.com/jQuery.post/