欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

Symfony2框架下一个简单Ajax留言板

程序员文章站 2022-05-02 23:14:09
...

<?php

namespace Dp\DriveplusBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Dp\DriveplusBundle\Entity\Messageboard;

class MessageController extends Controller
{    
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $query = $em->createQuery(
             'SELECT m FROM DpDriveplusBundle:Messageboard m ORDER BY m.id DESC'
         );
        $comments = $query->getResult();
        $count = count($comments);
        return $this->render('DpDriveplusBundle:Message:index.html.twig', array('comments'=>$comments, 'count'=>$count));
    }
    
    public function ajaxAction()
    {      
        $request = $this->getRequest();
        $ret = '';
             
        if ('POST' === $request->getMethod()) {       
            $name = $request->get('name');
            $message = $request->get('message');          
            $ret = '姓名:'.$name.'<br/> 留言内容:'.$message.'<hr/>';
            
            $comment = new Messageboard();
            $comment->setName($name);
            $comment->setMessage($message);
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($comment);       
            $em->flush();
            
            return new Response($ret);
        }
    }
}