如何检索记录而不必选择项目并单击输入

时间:2019-02-18 06:59:44

标签: php jquery html

我正在研究jquery-ui自动完成功能。我可以开始输入,并且从第一个字母开始,出现带有匹配项的下拉列表。该部分正常工作。我的问题是,当您从下拉列表中进行选择时。我已经尝试过onchangeonselect,但它们不起作用。最接近的代码是onclick,但是一旦从下拉列表中选择了一个条目,为了使脚本从数据库中检索记录,您必须再次在文本输入中单击。这是我描述的代码:

<script type="text/javascript">
$(function() {
$( "#autocomplete" ).autocomplete({
source: 'server.php'
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="ui-widget"> 
<input type="text" id="autocomplete" name="search" onclick="showMember(this.value)">
</div>
</div>
<div id="txtHint"></div>
<script>
function showMember(str) {
if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
} else { 
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;
        }
    };
    xmlhttp.open("GET","catlist.php?name="+str,true);
    xmlhttp.send();
}
}
</script>

server.php获取下拉列表的数据:

$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

$searchTerm = $_GET['term'];

$select =mysql_query("SELECT * FROM cmsb_markers WHERE name LIKE '".$searchTerm."%'");
while ($row=mysql_fetch_array($select)) 
{
$data[] = $row['name'];
}
echo json_encode($data);

然后catlist.php检索记录。

2 个答案:

答案 0 :(得分:1)

您应该从HTML节点中删除onselect方法,如下所示:

<input type="text" id="autocomplete" name="search">

然后,在您的自动完成功能上添加onselect事件,如下所示:

$(function() {
    $( "#autocomplete" ).autocomplete({
        source: 'server.php',
        onSelect: showMember(e, term, item)
     });
});

在这里,您需要从onSelect方法的传递参数中获取当前选定的项目值。您还需要在showMember函数中进行相应的修改。希望对您有帮助。

答案 1 :(得分:1)

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>jQuery Tests</title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
        <script>
        $(function(){
            $("#autocomplete").autocomplete({
                search: function( event, ui ) {
                    $('.loader').show();
                },
                source: function (request, response) {
                    $.ajax({
                        method: "get",
                        url: "server.php",
                        dataType: "json",
                        data: {
                            q: request.term
                        },
                        success: function (data) {
                            $('.loader').hide();
                            response(data);
                        },
                        error: function (jqXHR, exception) {
                            var msg = '';
                            if (jqXHR.status === 0) {
                                msg = 'Not connect.\n Verify Network.';
                            } else if (jqXHR.status == 404) {
                                msg = 'Requested page not found. [404]';
                            } else if (jqXHR.status == 500) {
                                msg = 'Internal Server Error [500].';
                            } else if (exception === 'parsererror') {
                                msg = 'Requested JSON parse failed.';
                            } else if (exception === 'timeout') {
                                msg = 'Time out error.';
                            } else if (exception === 'abort') {
                                msg = 'Ajax request aborted.';
                            } else {
                                msg = 'Uncaught Error.\n' + jqXHR.responseText;
                            }
                            alert(msg);
                        },
                    });
                },
                minLength: 1,
                select: function (event, ui) {
                    $("#autocomplete").val(ui.item ? ui.item.name : "");
                    showMember(ui.item.name);
                    return false;
                },
                change: function (event, ui) {
                    if (!ui.item) {
                        $("#autocomplete").val("");
                        $("#txtHint").val("");
                    }
                }
            }).autocomplete("instance")._renderItem = function (ul, item) {
                return $("<li>").append("<a>" + item.name + "</a>").appendTo(ul);
            };

            function showMember(str) {
                if (str == "") {
                    document.getElementById("txtHint").innerHTML = "";
                    return;
                } else { 
                    if (window.XMLHttpRequest) {
                        xmlhttp = new XMLHttpRequest();
                    } else {
                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xmlhttp.onreadystatechange = function() {
                        if (this.readyState == 4 && this.status == 200) {
                            document.getElementById("txtHint").innerHTML = this.responseText;
                        }
                    };
                    xmlhttp.open("GET","catlist.php?name="+str,true);
                    xmlhttp.send();
                }
            }
        });
        </script>
    </head>
    <body>
        <div id="wrapper">
            <div class="ui-widget"> 
                <input type="text" id="autocomplete" name="search" />
            </div>
        </div>
        <div id="txtHint"></div>
    </body>
</html>


<?php
//server.php
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

$searchTerm = $_GET['q'];

$select =mysql_query("SELECT * FROM cmsb_markers WHERE name LIKE '".$searchTerm."%'");
while ($row=mysql_fetch_array($select)) {
    $data[] = array("name" => $row['name']);
}
echo json_encode($data);