Typeahead建议:获取id而不是value并使用URL传递id

问题描述 投票:-1回答:1

我有一个PHP和Javascript代码,我用于我的预先搜索功能,它工作正常。但是如果你看下面的代码,我传递的是搜索值,我如何获取id并传递给表单URL?

HTML

<form method="get" class="form-inline customers" autocomplete="off" action="/customers/<?php echo id; ?> ">       
<input class="customers" id="customers" type="text" name="customers">
<button type="submit" title="Search Customers"></button>
</form>

使用Javascript

    <script>
    $( document ).ready(function() {
    $('input.customers').typeahead({
    source: function (query, process) {
var countrycode = '<?php echo $agencyid; ?>';
    return $.get('fetch_customers.php', { query: query, cc: countrycode }, function (data) {
    data = $.parseJSON(data);
    return process(data);
    });
    },
    });
    });
    </script>

PHP

$countrycode1 = $_GET['cc'];
 $sql="SELECT
       first_name,
       last_name,
       id,
       status,
       agency_id
       FROM customers
       WHERE (agency_id = '$countrycode1') AND first_name LIKE '%".$_GET['query']."%' LIMIT 20";
   $resultset = mysqli_query($conn, $sql) or die("database error:". 
   mysqli_error($conn));
   $json = array();
   while( $rowscity = mysqli_fetch_assoc($resultset) ) {
   $json[] = $rowscity["first_name"];
   $json[] = $rowscity["id"];
    }
   $output = json_encode($json);
   echo $output;
   mysqli_close($conn);
    ?>
php jquery typeahead
1个回答
0
投票

你的PHP脚本:

<?php

$countrycode1 = $_GET['cc'];
$sql = "SELECT
       first_name,
       last_name,
       id,
       status,
       agency_id
       FROM customers
       WHERE (agency_id = '" . $countrycode1 . "') AND first_name LIKE '%" . $_GET['query'] . "%' LIMIT 1";
$resultset = mysqli_query($conn, $sql) or die("database error:" . mysqli_error($conn));
$json = array();
while ($rowscity = mysqli_fetch_assoc($resultset)) {
    echo $rowscity["id"]; exit; 
}
?>

你的脚本可以像:

<script>
    $(document).ready(function () {
        $('input.customers').typeahead({
            source: function (query, process) {
                var countrycode = '<?php echo $agencyid; ?>';
                $.get('fetch_customers.php', {query: query, cc: countrycode}, function (data) {
                    $('form').attr('action', '/customers/' + data); 
                });
            },
        });
    });
</script>
© www.soinside.com 2019 - 2024. All rights reserved.