在 MVC 中使用 jquery ui 自动完成搜索 JSON 输出

Use jquery ui autocomplete to search JSON output in MVC

我正在尝试使用 jquery ui 自动完成小部件搜索我的用户 table。

我要搜索的用户 table 的两个字段:

TABLE `users`
 `user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
 `user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL


景色

<script>
$(function() {
    $.ajax({
        url: "/friend/showFriends", //the function in the controller
        dataType: "json",
        success: function(response){
            var data = $(response).map(function(){
                return {value: this.friend_usernames}; //I am pretty sure this is not correct?
            }).get();
            console.log(data);

        $("#searchFriends").autocomplete({
          source: data,
          minLength: 1
        });
      });
    });
});
</script>

<input type="search" id="searchFriends" placeholder="find friends"/>


控制器

/**
 * Show friends
 */
 public function showFriends()
 {
     $this->View->render('friend/index', array(
         'privateFriends' => FriendModel::displayFriends(),
         'searchFriends' => FriendModel::searchUsers()
      ));
 }


模特

/**
 * Search users table
 */
public static function searchUsers()
{
//if(isset($_GET['term'])) { /* Commented out for testing */
    $database = DatabaseFactory::getFactory()->getConnection();

    $query = $database->prepare("SELECT * FROM users WHERE (user_name LIKE :term or user_email LIKE :term) ORDER BY user_id LIMIT 5");

    $query->execute(array(':term' => '%'.$_GET['term'].'%'));

    $friends = $query->fetchAll();

    $friend_usernames = array(); 

    foreach($friends as $friend) { 
            $friend_usernames[] = $friend->user_name;
            $friend_usernames[] = $friend->user_email;
        }

    /* output results as json encoded array. */
    echo json_encode($friend_usernames);
    //}
}


输出

Notice: Undefined index: term
["user1","user1@email.com","user2","user2@email.com"]


所以我可以在网站上输出 JSON,但是我无法使用自动完成小部件搜索它!
有人可以帮帮我吗?
我没有使用任何类型的框架或 cms。

如果有任何帮助,我将非常高兴!

首先将 autocomplete="on" 设置为您的输入字段,即

<input type="search" id="searchFriends" placeholder="find friends" autocomplete="on"/>

然后把javascript写成

$("#searchFriends").focus(function(){

             $("#searchFriends").autocomplete({
                        autoFocus: true,
                        source:data,
                        minLength: 3, //search after two characters
                        select: function(event, ui){
                            //do something
                            //autofocus:true
                            },
                         autoFocus: true,
                        mustMatch: true,
                        html: false,
                        open: function(event, ui) {
                        $(".ui-autocomplete").css("z-index",2000);
                            }

                        });

        }).change(function() {
        if($('#searchFriends').val() != $('#searchFriends').data('selected-item')) {
            if($('.ui-autocomplete').length) {
                //$("#searchFriends").val('');
            }
        }
    });

并将其保存在 $(document).ready(function(){.....});

$(document).ready(function(){
var data=[];

    $.ajax({
        url: "/friend/showFriends", //the function in the controller
        dataType: "json",
        success: function(response){
            $.each(response, function(i,val){
            data.push(""+val.friend_usernames+"");
        });

        },
      });


$("#searchFriends").focus(function(){

             $("#searchFriends").autocomplete({
                        autoFocus: true,
                        source:data,
                        minLength: 3, //search after two characters
                        select: function(event, ui){
                            //do something
                            //autofocus:true
                            },
                         autoFocus: true,
                        mustMatch: true,
                        html: false,
                        open: function(event, ui) {
                        $(".ui-autocomplete").css("z-index",2000);
                            }

                        });

        }).change(function() {
        if($('#searchFriends').val() != $('#searchFriends').data('selected-item')) {
            if($('.ui-autocomplete').length) {
                //$("#searchFriends").val('');
            }
        }
    });
});

和HTML

<input type="search" id="searchFriends" placeholder="find friends" autocomplete="on"/>

我只能这样 do.This 对我来说很好,但对于其他数据库,请确保您从 AJAX 调用中正确获得 json 并且您有 jquery -自动完成插件和 jquery-ui-custom.x.x.x.js 以及 jquery 自动完成 css 插件。

我彻底检查了你的问题并最终解决了 it.The 主要问题是你的 json 格式没有出现 properly.It 应该以这种格式正常工作 -

[
    {
        "user_name": "user1",
        "user_email": "user1@email.com"
    },
    {
        "user_name": "user2",
        "user_email": "user2@email.com"
    }
]

我以某种方式在 PHP 的帮助下生成了 json,而不是通过数据库,不管是什么,它是通过 AJAX 通过 'url' 部分生成的。

好吧通过php检查我正在提供测试代码---

data.php

<?php 
$friend=array(
        array("user_name"=>"user1","user_email"=>"user1@email.com"),
        array("user_name"=>"user2","user_email"=>"user2@email.com")
        );

        echo json_encode($friend);

?>

完整的 html 和 javascript 代码一起是

<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
var data=[];

    $.ajax({
        url: "data.php", //the function in the controller
        dataType: "json",
        success: function(response){
            //console.log(response);
            $.each(response, function(i,val){
            data.push(""+val.user_name+"");//to display names in auto-complete
            data.push(""+val.user_email+"");//to display emails in auto-complete
        });

        },
      });


$("#searchFriends").focus(function(){
             $("#searchFriends").autocomplete({
                        autoFocus: true,
                        source:data,
                        minLength: 1, 
                        select: function(event, ui){
                            //do something
                            //autofocus:true
                            },
                         autoFocus: true,
                        mustMatch: true,
                        html: false,
                        open: function(event, ui) {
                        $(".ui-autocomplete").css("z-index",2000);
                            }

                        });

        }).change(function() {
        if($('#searchFriends').val() != $('#searchFriends').data('selected-item')) {
            if($('.ui-autocomplete').length) {
                //$("#searchFriends").val('');
            }
        }
    });
});
</script>
</head>
<body>
<div class="col-md-3">
    <input type="search" id="searchFriends" class="form-control" placeholder="find friends" autocomplete="on"/>
</div>
</body>
</html>

就是这样,它工作正常。
测试一下 ---

1> 创建一个'index.html'文件,将html和javascript代码复制进去,所有链接都取自cdn,只需要互联网连接即可。

2> 创建一个 'data.php' 文件并将 php 代码复制到其中,并将此文件保存在与 'index.html' 相同的文件夹中。不需要数据库(用于测试目的)。

3>运行它。

N.B.*** 要使用您的数据库获得结果,您需要将传入的 json 格式设置为我上面给出的格式。

我希望最后是 done.Thanks。