加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Symfony2 – Ajax搜索

发布时间:2020-12-13 17:31:03 所属栏目:PHP教程 来源:网络整理
导读:我正在开发一个Symfony2项目,我有一个用户实体,我需要一个ajax搜索栏来搜索我的用户. 问题是在我的 AJAX响应中,控制器由于某种原因返回数据库中的所有用户. JS $('#search').keyup(function() { searchText = $(this).val(); $.ajax({ type: "GET",url: "/Ap
我正在开发一个Symfony2项目,我有一个用户实体,我需要一个ajax搜索栏来搜索我的用户.
问题是在我的 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 SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;

use SymfonyComponentSerializerSerializer;
use SymfonyComponentSerializerEncoderXmlEncoder;
use SymfonyComponentSerializerEncoderJsonEncoder;
use SymfonyComponentSerializerNormalizerGetSetMethodNormalizer;

use ApanaBundleMainBundleEntityUser;

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

如果我为我的字符串参数提供静态文本并访问控制器的路由,它可以正常工作.

解决方法

所以答案是改变以下内容:

$.ajax({
        type: "GET",[...]

$.ajax({
        type: "POST",[...]

你可能实际上没有得到GET参数并不奇怪:How to get the request parameters in symfony2

public function updateAction(Request $request)
{
    // $_GET parameters
    $request->query->get('name');

    // $_POST parameters
    $request->request->get('name');

并且还有其他一些可能的方法.它也可以解决你的问题,但如果你不需要,最好不要使用GET.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读