3
我正在一個Symfony2項目,我有一個用戶實體,我需要一個Ajax搜索欄來搜索我的用戶。 問題是,在我的AJAX響應中,控制器出於某種原因從數據庫返回所有用戶。Symfony2 - Ajax搜索
JS
$('#search').keyup(function() {
searchText = $(this).val();
$.ajax({
type: "GET",
url: "/Apana/web/app_dev.php/search",
dataType: "json",
data: {searchText : searchText},
success : function(response)
{
console.log(response);
}
});
});
控制器
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Apana\Bundle\MainBundle\Entity\User;
class SearchController extends Controller
{
public function liveSearchAction(Request $request)
{
$string = $this->getRequest()->request->get('searchText');
//$string = "alfa";
$users = $this->getDoctrine()
->getRepository('ApanaMainBundle:User')
->findByLetters($string);
//return users on json format
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$jsonContent = $serializer->serialize($users, 'json');
$response = new Response($jsonContent);
return $response;
}
}
用戶系統信息庫
class UserRepository extends EntityRepository
{
public function findByLetters($string){
return $this->getEntityManager()->createQuery('SELECT u FROM ApanaMainBundle:User u
WHERE u.firstname LIKE :string OR u.lastname LIKE :string')
->setParameter('string','%'.$string.'%')
->getResult();
}
}
如果我給我的字符串參數的靜態文本,並參觀了控制器的路線,它的工作原理精細。
您是否檢查過該值是否傳遞給了JavaScript?您可能還想嘗試'type:「POST」'並嘗試發回字符串以進行調試。 –
奇怪的是,只是將類型更改爲「POST」...並且完美無缺! – Achilles