php - 自动完成搜索框,从结果中选择多个值

标签 php mysql ajax forms search

我正在使用 php/mysql 创建自己的食谱框,而我所坚持的一部分实际上是创建食谱,特别是选择成分。

我想做的是有一个自动完成搜索框,我可以在其中输入成分名称,将结果下拉到正下方,然后单击我要查找的内容。单击成分后,它将列在搜索框下方,其中包含用于输入数量的输入和用于在需要时删除的“x”。当然,这会根据食谱需要的成分数量而增长。最后,我只需获取数据并将其插入到我的数据库中。

我看过很多关于获取自动完成搜索框功能的 AJAX 教程,但没有将其与值选择联系起来。我想要的最好的例子可以在 http://supercook.com 找到。 。他们有它,所以你可以搜索食谱。

有什么建议或在线资源吗?

谢谢!

最佳答案

你问了一个很好的问题。下面我写了一个简短的示例来帮助您入门。只需将其保存为成分.php 就可以了。当然,您需要添加数据库连接和查询才能为其提供真实数据。我使用了 jQuery 库,因为它使 Javascript 部分变得更加容易。

<?php

// connect to database here

if (isset($_POST['q'])) {
    if (trim($_POST['q']) === '') die('[]');
    // $q = mysql_real_escape_string($_POST['q']);
    // run a query like: "SELECT id, name FROM ingredients WHERE name LIKE '{$q}%'"
    // and put the result in the $result array.
    // This is sample data:
    $result = array(
        array('id' => 71, 'name' => 'apple'),
        array('id' => 3, 'name' => 'anchovies'),
        array('id' => 230, 'name' => 'artichoke'),
        );

    if (function_exists('json_encode')) die(json_encode($result));
    else {
        $escaped = array();
        foreach ($result as $r) $escaped[] = str_replace(array('\\', '"'), array('\\\\', '\"'), $r);
        die('["'.join('","', $escaped).'"]');
    }
}

$data = array();
if (isset($_POST['ingredients'])) {
    foreach ($_POST['ingredients'] as $i => $ingredient) {
        $data[] = array(
            'ingredient' => $ingredient,
            'quantity' => $_POST['quantities'][$i],
            );
    }
    // save data to the database here (or inside the foreach loop above)
}

?>
<html><head></head><body>
<style>
    #wrap { position: relative }
    #pop {
        position: absolute;
        border: 1px solid black;
        background-color: white;
        display: none;
    }
</style>

<?php if (count($data)): ?>
<h3>Saved:</h3>
<pre><?php print_r($data) ?></pre>
<?php endif; ?>

<div id="wrap">
    <input id="adder" />
    <div id="pop"></div>
</div>
<form method="post">
    Ingredients:<br />
    <div id="recipe"></div>
    <input type="submit" value="Save" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
    var last_query = '';
    jQuery(function() {
        jQuery('#adder').val('').keyup(function() {
            var query = jQuery(this).val();
            if (query != last_query) jQuery.post('ingredients.php', {q: query}, function(data) {
                var p = jQuery('#pop').html('').show();
                for (var i=0; i<data.length; i++) {
                    p.append(jQuery('<p>'+data[i].name+'</p>').bind('click', { ingredient: data[i] }, function(e) {
                        add_ingredient(e.data.ingredient);
                        jQuery('#pop').hide();
                        jQuery('#adder').val('');
                    }));
                }
            }, 'json');
            else jQuery('#pop').show();
            last_query = query;
        });
    });
    function add_ingredient(data) {
        console.log(data);
        var ingredient = jQuery('<div> <input name="quantities[]" size="2" /> '+data.name
            + '<input type="hidden" name="ingredients[]" value="'+data.id+'" /></div>');
        var remover = jQuery('<span>X</span>').click(function() {
            jQuery(this).parent().remove();
        });
        jQuery('#recipe').append(ingredient.prepend(remover));
    }
</script>
</body></html>

关于php - 自动完成搜索框,从结果中选择多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3243140/

相关文章:

javascript - 将 Canvas 图像传递给 php

mysql - 按月分组并添加多列

php - 一切都在 UTF8 上,但我仍然得到奇怪的字符,例如 �

php - 如何通过 php 将 sql 查询的结果显示到 php 页面上?

javascript - 在 Jscript 弹出窗口中显示 PHP 结果

php - mysql查询为分组数据返回错误

php - Voyager 安装 Laravel 上的外键约束格式不正确

javascript - 在 php 中完成流程后更改 JS/jQuery 中的按钮文本

php - 从 # 之后的 URL 解析 Facebook token

php - 每次加载页面时如何更新 MySQL 表?