jQuery 自动完成从数据库中检索数据

jQuery autocomplete retrieve data from database

本文关键字:数据库 检索 数据 jQuery      更新时间:2023-09-26

我已经为我的网络实现了jQuery自动完成功能,它工作正常。但是我希望自动完成的结果仅检索特定人员的数据,而不是完整的数据库结果。

下面是用于自动完成的 jQuery

jQuery(document).ready(function($){
$('.product_desc').autocomplete({source:'functions/products.php?', minLength:2});

产品.php

//Path for the databsae
<?php
include '../include/configuration.php';
if ( !isset($_REQUEST['term']) )
    exit;
$rs = mysql_query('select id,item_name,fk_vendor_id from item where item_name like "%'. mysql_real_escape_string($_REQUEST['term']).'%" order by item_name asc ', $con);
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
    while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
    {
        $data[] = array(
            'label' => $row['item_name'],
            'value' => $row['item_name']
        );
    }
}
else 
{
    $data[] = array(
        'label' => 'not found',
        'value' =>''
    );
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>

任何解决方案都将不胜感激。

试试这个:

$(".product_desc").autocomplete({
source: "functions/products.php",
minLength: 2,
select: function(event,ui){
    //do something
    }
});

试试这段代码,任何具有类.search自动完成建议的文本字段都将在 ajax 中的服务器端工作.php您需要返回如下数组:

$response = ['Computer', 'Mouse', 'Keyboard', 'Monitor'];
echo json_encode($response);

这是自动建议的示例代码。

$(document).on('keyups','.search',function() {
        $(this).autocomplete({
            source: function( request, response ) {
                if (request.term != "") {
                    $.ajax({
                        url: "ajax.php",
                        dataType: "json",
                        method: "post",
                        data: {
                            name: request.term
                        },
                        success: function (data) {
                            if (data != "") {
                                response($.map(data, function (item) {
                                    var name = item.name;
                                    return {
                                        label: name,
                                        value: name,
                                        data: item
                                    }
                                }));
                            }
                        }
                    });
                }
            },
            autoFocus: true,
            minLength: 2,
            select: function( event, ui ) {
                var name = ui.item.data;
                $(this).val(name);
            }
        });
    });