【问题标题】:Use jquery ui autocomplete to search JSON output in MVC使用 jquery ui 自动完成在 MVC 中搜索 JSON 输出
【发布时间】:2015-05-16 04:02:06
【问题描述】:

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

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

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);
    //}
}


输出

注意:未定义索引:术语
["user1","user1@email.com","user2","user2@email.com"]


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

任何形式的帮助我都会非常高兴!

【问题讨论】:

  • 也许您应该返回 json_encode($friend_usernames) 而不是回显。如果这不起作用,请尝试对 Javascript 数组进行硬编码,以确保自动完成对自身起作用
  • 非常感谢您的回答!返回而不是回声没有帮助。我现在将尝试您的第二个建议。
  • 自动完成功能正在运行。我觉得这部分是问题所在: var data = $(response).map(function(){ return {value: this.friend_usernames};

标签: javascript jquery json autocomplete jquery-ui-autocomplete


【解决方案1】:

首先将 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(){.....});

【讨论】:

  • 感谢您的回答!不幸的是,它仍然不起作用。我也没有看到它会在哪里调用控制器功能?源设置为数据或者它是如何工作的?
  • 您的回答对我帮助很大!如果您能帮助我克服这最后一道障碍,我将不胜感激!
  • 你有没有加载jquery自动完成插件并将代码保存在$(document).ready(function(){.....}); ?
  • 我只改变了自动完成功能,其余的和你做的一样,我再次发布完整的javascript。
【解决方案2】:
$(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"/>

这就是我所能做的。这对我来说很好,但对于其他数据库,请确保您从 AJAX 调用中正确获取 json,并且您有 jquery-autocomplete 插件和 jquery-ui-custom.xxxjs 以及 jquery auto - 完整的 css 插件。

【讨论】:

  • 谢谢!!我误解了你的代码。我用它代替了我的。这就是为什么它对我没有任何意义。现在,它更有意义了。不幸的是,仍然没有解决我的问题。谢谢你的所有努力!
【解决方案3】:

我彻底检查了你的问题,终于解决了。主要问题是你的 json 格式没有正常工作。它应该以这种格式正常工作 -

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

不知何故,我在 PHP 的帮助下生成了 json,而不是通过数据库,不管是什么,它都是通过 AJAX 的“url”部分来的。

通过 php 进行检查,我正在提供测试代码 ---

数据.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>运行它。

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

我希望它终于完成了。谢谢。

【讨论】:

  • 太棒了!非常感谢!!
  • 在测试中它正在工作!在我的项目中还没有。但是您对我的 json 格式是正确的,所以我很确定一旦我弄清楚如何正确使用格式,它也将在我的项目中工作!终于我知道了,问题是什么,现在我知道要研究什么了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 2012-07-11
相关资源
最近更新 更多