我试图让下面的jQuery脚本使用AJAX。当我手动定义<input type="text" id="search-names">
:
UserArray
)
$(function() {
var UserArray = [
{"label": "Member#1 of User1", "value": "user1"},
{"label": "Member#1 of User2", "value": "username2"},
{"label": "Member#2 of User2", "value": "username2"},
{"label": "Member#2 of User1", "value": "user1"},
{"label": "Member#3 of User1", "value": "user1"}
];
$("#search-names").autocomplete({
//source: "/member/search",
source: UserArray,
minLength: 2,
select: function (event, matched) {
console.log(matched)
window.location = window.location + '?_switch_user=' + matched.item.value
}
});
})
但是,之前我没有使用过AJAX,所以我不确定我错过了什么让我从另一条路线(/member/search
)中提取数据。我的JSON控制器是:
/**
* @Route("/member/search", name="membersearch")
*/
public function memberSearch(Request $request)
{
$response = new Response();
$members = $this->getDoctrine()->getRepository('AppBundle:Members')->membersAndUsernames() ;
foreach($members as $member) {
$data[]=array($member->getFirstname(). ' '.$member->getSurname() . ' '.$member->getMemberId()->getUsername() );;
}
$response->setContent(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
$response->send();
}
....这似乎将数据返回给我:
[["Member#1 of User1", "user1"],["Member#1 of User2", "username2"]],
...而不是:
[{"label": "Member#1 of User1", "value": "user1"},{"label": "Member#1 of User2", "value": "username2"}]
答案 0 :(得分:0)
在我看来,问题在于以下几行:
$data[]=array($member->getFirstname(). ' '.$member->getSurname() . ' '.$member->getMemberId()->getUsername() );;
尝试将其更改为以下内容:
$data[]=array('value' => $member->getMemberId()->getUsername(),
'label' => $member->getFirstname().' '.$member->getSurname()
);