我正在尝试使用jquery ui自动填充小部件来搜索我的用户表。
从我的用户表,这两个领域,我想寻找:
使用jquery ui自动完成在MVC中搜索JSON输出
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”, “[email protected]”, “user2”,“[email protected]”]
所以我能够在网站上输出JSON,但是我无法使用自动填充小部件搜索它!
请问有人可以帮我吗?
我没有使用任何一种框架或cms。
我会很高兴任何形式的帮助!
也许你应该返回你的'json_encode($ friend_usernames)'而不是echo。如果这不起作用,请尝试对Javascript数组进行硬编码以确保自动完成自身工作 – Flame 2015-03-13 15:42:05
非常感谢您的回答!返回而不是回声没有帮助。我现在会尝试你的第二个建议。 – Schwesi 2015-03-13 15:53:48
自动完成本身正在工作。我有这样的感觉,这部分是问题所在:var data = $(response).map(function(){ return {value:this.friend_usernames}; – Schwesi 2015-03-13 16:10:42