与Symfony3的Ajax

时间:2017-02-12 18:48:06

标签: ajax twig symfony

我想动态显示用户列表,但它不起作用。我自己测试了查询,它运行得很好,但它仍然没有显示任何内容。这是脚本

 <script>
    function showUser() {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("user-list-div").innerHTML = xmlhttp.responseText;
                }
            };
            xmlhttp.open("GET","{{ path('ajax_update')}}",true);
            xmlhttp.send();
        }
</script>

这是控制器动作:

 public function searchUsersAction(Request $request)
{
    /*$em = $this->getDoctrine()->getManager();
    $request = $this->get('request');*/
    $projectName = $request->get('projectName');
    echo($projectName);
    //$projectId=$this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findName($projectName);
    //echo(count($projectId));
    //foreach($projectId as $pId) {
        //$projectId->getPId();
        $pus = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUsers($projectName);
    //}
    $response = "<select class=\"select2_multiple form-control\" multiple=\"multiple\">";
    foreach($pus as $user){
        $response . "<option>" . $user . "</option>";
    }
    $response = $response."</select> ";
    return new Response($response);
    //return($pus);
    //call repository function
}

这是查询

public function findProjectUsers($projectName){
    $query=$this->getEntityManager()
        ->createQuery(
            "SELECT u.firstName FROM SocialProDefaultBundle:User u, SocialProProjectBundle:Project p, SocialProProjectBundle:ProjectUser pu WHERE u.id = pu.user AND p.id=pu.project AND p.name='$projectName'");
    return $query->getResult();
}

2 个答案:

答案 0 :(得分:0)

您的查询不正确。你需要连接$ projectName,如下所示:

public function findProjectUsers($projectName){
    $query=$this->getEntityManager()
        ->createQuery(
            "SELECT u.firstName
                FROM SocialProDefaultBundle:User u,
                SocialProProjectBundle:Project p,
                SocialProProjectBundle:ProjectUser pu
                WHERE u.id = pu.user AND p.id=pu.project AND p.name=:name"
        )->setParameter('name', $projectName);
    return $query->getResult();
}

我不确定这是否会解决所有问题,但至少会让查询正常运行。

答案 1 :(得分:0)

我不是很清楚你的问题,但是看楼上的朋友说你的查询有问题,所以我在想,你可以把控制器,查询做断点调试。然后错误精确锁定位置。我解决这个问题的思路是如此普遍。