在Symfony 3.4中使用AJAX从控制器在树枝中加载数据

时间:2019-03-29 03:48:01

标签: json ajax symfony

我正在尝试使用AJAX从控制器加载树枝中的数据, 这是我的控制器操作:

    public function ajaxAction(Request $request) {
        $students = $this->getDoctrine()
            ->getRepository('techeventBundle:event')
            ->findAll();
        if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
       echo "request successfull";
            $jsonData = array();
            $idx = 0;
            foreach($students as $student) {
                $temp = array(
                    'name' => $student->getTitre(),
                    'address' => $student->getDescription(),
                );
                $jsonData[$idx++] = $temp;
            }
            return new JsonResponse($jsonData);
        } else {
            return $this->render('@reservation/Default/ajax.html.twig');
        }
    }

这是我的树枝文件:

    <!--  test Ajax --->
    <button id="loadstudent">load events</button>
    <div id="student">
        <div id="name"></div>
        <div id="address"></div>
    </div>
    <!--  test Ajax --->
    <script language = "javascript"
            src = "https://code.jquery.com/jquery-2.2.4.min.js"></script>

    <script language = "javascript">
        $(document).ready(function(){
            $("#loadstudent").on("click", function(event){
                $.ajax({
                    url:        '/student/ajax',
                    type:       'POST',
                    dataType:   'json',
                    async:      true,

                    success: function(data, status) {
                        var e = $('<tr><th>Name</th><th>Address</th></tr>');
                        $('#student').html('');
                        $('#student').append(e);

                        for(i = 0; i < data.length; i++) {
                            student = data[i];
                            var e = $('<tr><td id = "name"></td><td id = "address"></td></tr>');

                            $('#name', e).html(student['name']);
                            $('#address', e).html(student['address']);
                            $('#student').append(e);
                            alert('Ajax request success');

                        }
                    },
                    error : function(xhr, textStatus, errorThrown) {
                        alert('Ajax request failed.');
                    }
                });
            });
        });
    </script> 

让我向您描述问题,当我单击按钮(“ #loadstudent”)时,它会显示“ Ajax请求失败”警报,此外,如果您在我的操作代码中看到了“我添加了echo”请求成功”;之后:

        if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {

它没有显示出来,这意味着它没有进入条件!帮忙,请问我一个星期以来一直陷入这个问题,

1 个答案:

答案 0 :(得分:0)

在控制器@Route("/student/ajax", name="get-students")中添加路由名称

示例:

 /**
 * @Route("/student/ajax", name="get-students")
 */
  public function ajaxAction(Request $request) {          
    if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) { 
        $jsonData = array(
            array(
                'name' => 'name1',
                'address' => 'addres1',
            ),
              array(
                'name' => 'name2',
                'address' => 'addres2',
            ),
        );

        return new JsonResponse($jsonData);
    } else {
        return $this->render('@reservation/Default/ajax.html.twig');
    }
}

现在,在$.ajax中将请求发送到路由名称url: "{{ path('get-students') }}"

 <script language = "javascript">
        $(document).ready(function () {
            $("#loadstudent").on("click", function (event) {
                $.ajax({
                    url: "{{ path('get-students') }}",
                    type: 'POST',
                    dataType: 'json',
                    async: true,

                    success: function (data, status) {
                        var e = $('<tr><th>Name</th><th>Address</th></tr>');
                        $('#student').html('');
                        $('#student').append(e);

                        for (i = 0; i < data.length; i++) {
                            student = data[i];
                            var e = $('<tr><td id = "name"></td><td id = "address"></td></tr>');

                            $('#name', e).html(student['name']);
                            $('#address', e).html(student['address']);
                            $('#student').append(e);
                            alert('Ajax request success');

                        }
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        console.log(xhr, textStatus, errorThrown);
                        alert('Ajax request failed.');
                    }
                });
            });
        });
    </script> 

Twig文件输出:

Name    Address
name1   addres1
name2   addres2