请帮我解决自动填充问题

时间:2011-06-16 15:16:47

标签: php jquery mysql jquery-ui autocomplete

我想将“具有多个值的Jquery UI自动完成”应用于一个注册表单输入字段。

我想要做的事情:当访问者为此输入字段键入现有用户的名称时,首先,脚本搜索名称存在,完成它(如果存在),添加逗号。用户可以在此字段中键入第二个,第三个...现有用户名,并且每次脚本都将自动完成。当访问者点击提交按钮时,PHP搜索此用户名的id,创建id的数组,将其添加到db表中的新用户“friends”字段。

我的代码:

HTML

<form action="index.php" method="post">      
<input class="std" type="text" name="friends"  id="friends"/>
<input type="submit" name="submit">
</form>

Jquery的

$(function() {
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#friends" )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                $.getJSON( "search.php", {
                    term: extractLast( request.term )
                }, response );
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
});

这是来自示例文件夹的原始php文件,完美运行。但我想从数据库而不是数组中获取 原始search.php

$q = strtolower($_GET["term"]);
if (!$q) return;
$items = array(
"Great Bittern"=>"Botaurus stellaris",
"Little Grebe"=>"Tachybaptus ruficollis",
"Black-necked Grebe"=>"Podiceps nigricollis",
"Little Bittern"=>"Ixobrychus minutus",
"Black-crowned Night Heron"=>"Nycticorax nycticorax",
"Purple Heron"=>"Ardea purpurea",
"White Stork"=>"Ciconia ciconia",
"Spoonbill"=>"Platalea leucorodia",
"Red-crested Pochard"=>"Netta rufina",
"Common Eider"=>"Somateria mollissima",
"Red Kite"=>"Milvus milvus",

);

function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }

    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

            // We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
            if( is_numeric($key) ){
                $key = "key_$key";
            }
            $key = "\"".addslashes($key)."\"";

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "\"".addslashes($value)."\"";
            }

            // Add to staging array:
            $construct[] = "$key: $value";
        }

        // Then we collapse the staging array into the JSON form:
        $result = "{ " . implode( ", ", $construct ) . " }";

    } else { // If the array is a vector (not associative):

        $construct = array();
        foreach( $array as $value ){

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "'".addslashes($value)."'";
            }

            // Add to staging array:
            $construct[] = $value;
        }

        // Then we collapse the staging array into the JSON form:
        $result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return $result;
}

$result = array();
foreach ($items as $key=>$value) {
    if (strpos(strtolower($key), $q) !== false) {
        array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
    }
    if (count($result) > 11)
        break;
}
echo array_to_json($result);

更改了search.php

$conn = mysql_connect("localhost", "user", "pass");
mysql_select_db("db", $conn);
$q = strtolower($_GET["term"]);
$query = mysql_query("select fullname from usr_table where fullname like %$q%");
$results = array();
while ($row = mysql_fetch_array($query)) {
    array_push($results, $row);
}
echo json_encode($results);

自动填充对我不起作用。找不到错误的代码部分。请帮忙解决这个问题。抱歉我的英文不好

1 个答案:

答案 0 :(得分:0)

您提到要创建一个ID数组(很可能与每个搜索过的名称相关联)?

在您的SQL语句中,包含您的ID字段。

$query = mysql_query("select id, fullname from usr_table where fullname like %$q%");

然后,而不是

array_push($results,$row)

尝试:

$results[] = array( $row[0] => $row[1] ); 

这应该遵循与search.php中的静态数组相同的数组结构,然后在进行JSON编码后对其进行修改。我不确定您的自动填充功能会作为结果输出哪个,因此请尝试此操作(switch row[0] with row[1]

$results[] = array( $row[1] => $row[0] );

编辑:

现在,我知道JSON编码的数组需要看起来像什么。这样做:

$results[] = array ( "id" => $row[0] , "label" => $row[1], "value" => $row[1] );

上面将数组附加到结果数组。让我知道这个是否奏效。它相当于array_push

array_push($results, array ( "id" => $row[0] , "label" => $row[1], "value" => $row[1] ));