php jQuery 自动完成(远程) - 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5905560/
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-08-25 22:50:24  来源:igfitidea点击:

jQuery Autocomplete (Remote) - example

phpjquerymysqlautocomplete

提问by dwarbi

I was really hoping to avoid posting a new question, but I cannot find a functioning example of the jQuery Autocomplete Remote feature that includes both the calling page and the "search" page. The jQueryUI "Demos & Documentation" section doesn't include the source of "search.php"

我真的希望避免发布新问题,但我找不到包含调用页面和“搜索”页面的 jQuery 自动完成远程功能的功能示例。jQueryUI“演示和文档”部分不包括“search.php”的来源

I've tried dozens of combinations, but here's what I started with:

我已经尝试了几十种组合,但这是我开始的:

<style>
    .ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
    </style>
    <script>
    $(function() {
        function log( message ) {
            $( "<div/>" ).text( message ).prependTo( "#log" );
            $( "#log" ).attr( "scrollTop", 0 );
        }

        $( "#birds" ).autocomplete({
            source: "search.php",
            minLength: 1,
            select: function( event, ui ) {
                log( ui.item ?
                    "Selected: " + ui.item.value + " aka " + ui.item.id :
                    "Nothing selected, input was " + this.value );
            }
        });
    });
    </script>



<div class="demo">

<div class="ui-widget">
    <label for="birds">Birds: </label>
    <input id="birds" />
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
    Result:
    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

</div>

and search.php:

和search.php:

    $conn = mysql_connect("localhost", "USERNAME", "PASSWORD");
    mysql_select_db("DATABASE", $conn);
    $q = strtolower($_GET["birds"]);

    $query = mysql_query("select FIELD from TABLE where FIELD like '%$q%'");
    while ($row = mysql_fetch_array($query)) {
    echo json_encode($row);
}

Does anyone have code snippets that show both sides of this equation that they can share? Thanks so much to any help you can provide.

有没有人有代码片段显示他们可以共享的这个等式的两边?非常感谢您提供的任何帮助。

回答by dwarbi

Here is the correct code for search.php:

这是 search.php 的正确代码:

    $conn = mysql_connect("localhost", "USERNAME", "PASSWORD");
    mysql_select_db("DATABASE", $conn);
    $q = strtolower($_GET["term"]);

$return = array();
    $query = mysql_query("select FIELD from TABLE where FIELD like '%$q%'");
    while ($row = mysql_fetch_array($query)) {
    array_push($return,array('label'=>$row['FIELD'],'value'=>$row['FIELD']));
}
echo(json_encode($return));

Some key points

一些关键点

  • The word termis nowhere in the sample calling page given by jqueryui, but this is the Querystring name used
  • You must create an array of the value, and then json encode before returning
  • jqueryui给出的示例调用页面中没有term这个词,但这是使用的Querystring名称
  • 你必须创建一个值的数组,然后在返回之前进行json编码

I hope this helps some folks out in the future!

我希望这对未来的一些人有所帮助!

回答by Joshua - Pendo

There are a couple of larger tutorials when you google for 'jQuery UI Autocomplete Tutorial', I suppose on of these might be of any help: http://www.google.com/search?q=jqueryUI+autocomplete+tutorial

当你在谷歌搜索“jQuery UI 自动完成教程”时,有几个更大的教程,我想其中一个可能有帮助:http: //www.google.com/search?q=jqueryUI+autocomplete+tutorial

回答by crockpotveggies

Here is a trimmed version of an autocomplete I have previously used. Might have an error or two since I cut some code out.

这是我以前使用过的自动完成的修剪版本。因为我删掉了一些代码,所以可能会有一两个错误。

On the server:

在服务器上:

    if(isset($_POST['queryString'])) {
    $queryString = $_POST['queryString'];
    $html = '';

    if(strlen($queryString) >1) {
        $names= explode(" ", $queryString ); 
        foreach ($names as &$value) {
            // step 1: first names
            $result= queryf("SELECT *, 
                    MATCH(productName, productTags, productCategory, productOneLine) 
                    AGAINST ('*$queryString*' IN BOOLEAN MODE) 
                    AS score FROM products
                    WHERE MATCH(productName, productTags, productCategory, productOneLine) 
                    AGAINST ('*$queryString*' IN BOOLEAN MODE)
                    AND productStatus='1'
                    ORDER BY score DESC
                    LIMIT 10") ;
            if($result) {
while ($row = mysql_fetch_array($result)) {
                            echo '<li onclick="location.href=\'/'.$row['productCategory'].'/'.$row['productSlug'].'/\';" style="cursor: pointer;"><a href="/'.$row['productCategory'].'/'.$row['productSlug'].'/">
                            <div class="resultImg"><img src="/image.php?width=24&height=24&image='.$row['productIcon'].'" /></div> 
                            <span class="productName">'.$row['productName'].'</span><br />
                            '.$row['productOneLine'].'</a></li>';
                        }

                    }
        } else {
                    echo '
                <ul>
                    <li>
                    <div class="resultImg"><img src="/image.php?width=24&height=24&image=/images/icon_searching.gif" /></div> 
                    <span class="productName">Processing...</span><br />
                    Please keep typing while we process your code</li>
                </ul>';
                }
        }
    } else {
        echo '
                <ul>
                    <li>
                    <div class="resultImg"><img src="/image.php?width=24&height=24&image=/images/icon_searching.gif" /></div> 
                    <span class="productName">Processing...</span><br />
                    Please keep typing while we process your code</li>
                </ul>';
    }
} else {
    echo 'Nothing to see here.';
}

The script:

剧本:

function suggest(inputString){
    if(inputString.length == 0) {
        $('#suggestions').fadeOut();
    } else {
    $('#country').addClass('load');
        $.post("/autosuggest.php", {queryString: ""+inputString+""}, function(data){
            if(data.length >0) {
                $('#suggestions').fadeIn();
                $('#suggestionsList').html(data);
                $('#country').removeClass('load');
            }
        });
    }
}
function fill(thisValue) {
    $('#country').val(thisValue);
    setTimeout("$('#suggestions').fadeOut();", 600);
}

And on the XHTML page:

在 XHTML 页面上:

<div id="bg_searchMain">
                        <form id="form" action="#">
                        <input type="text" style="float:left; display:inline; width:430px; margin:5px 0 0 5px; background:none; border:none;" value="" id="country" onkeyup="suggest(this.value);" onblur="fill();" autocomplete="off" />
                        <!--<img src="images/button_search.gif" alt="Find" id="button_search" />-->
                        <div class="suggestionsBox" id="suggestions" style="display: none;">
                            <div class="suggestionList" id="suggestionsList"> &nbsp; </div>
                        </div>

                        </form>
                    </div>

The comments about "acceptance rate" are unnecessary it's more useful to post this for Google than for reputation.

关于“接受率”的评论是不必要的,为 Google 发布此内容比为声誉发布更有用。

回答by Bineesh

I did the php like & it was successful, I was using mysqli method.

我做了 php like & 它成功了,我使用的是 mysqli 方法。

    $q = strtolower($_GET["term"]);

    $return = array();
    $query = "select name from students where name like '%$q%'";
    $result=$conn->query($query);
            while ($cresult=$result->fetch_row()){array_push($return,array('label'=>$cresult[0],'value'=>$cresult[0]));
    }
    echo(json_encode($return));

?>

?>