duanruanxian5028 2015-08-21 10:45
浏览 68
已采纳

从控制器获取数据,然后通过ajax打印

I have print action, witch get all my records from db

public function printAction()
{
    $users = $this->getDoctrine()->getRepository('ModelBundle:Users')->findAll();
    $resp = new JsonResponse($users, 200);
    return $resp;
}

I want use this data and print via ajax in div element, but i cant understand, how i can do it. Maybe anybody know. Please, help me.

  • 写回答

3条回答 默认 最新

  • dongshun7312 2015-08-21 10:58
    关注

    Do you have a serializer in your user entity? Because you are getting all users as entities. I suggest you to do something like this:

    When you click a button or any element, call your route like this:

    //change this element to your button
    $('a.press-me').click(function() {
        $.ajax({
            url: 'YOUR ROUTE HERE',
            dataType: 'HTML',
            success: function (data) {
                $('#your-div').html(data);
            }
        });
    });
    
    //create a view users.html.twig or something like that...
    {% if users is defined and users is not empty %}
        {% for user in users %}
            Name: {{ user.name }}
        {% endfor %}
    {% else %}
        <p class="error">No data!</p>
    {% endif %}
    
    //add this line to top of your controller
    use Symfony\Component\HttpFoundation\Request;
    
    //add request variable to your action
    public function printAction(Request $request)
    {
        //you want to get users via ajax right? so check if the request is ajax or not
        if($request->isXmlHttpRequest()) {
            // Get all users
            $users = $this->getDoctrine()->getRepository('ModelBundle:Users')->findAll();
    
        //render a view and pass it as variable
        return $this->renderView('ModelBundle:Default:users.html.twig', ['users'] => $users);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据