我对symfony控制器有一些问题,为什么要发送ajax请求。
这是我的控制器
namespace AppBundle'Controller;
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Route;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use Symfony'Component'HttpFoundation'Request;
use AppBundle'Entity'Follow;
use AppBundle'Exception'FollowException;
class FollowController extends Controller
{
public function ajaxAction(Request $request)
{
$authChecker = $this->get('security.authorization_checker');
if(!$authChecker->isGranted('ROLE_USER')) {
echo 'Access Denied';
}
$userId = $request->request->get('id');;
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$followedUser = $em->getRepository('AppBundle:User')->find($userId);
if(!$followedUser) {
echo 'User not exist';
}
$follow = new Follow();
$follow->setUserId($followedUser->getId());
$follow->setFollowerId($user->getId());
$em->persist($follow);
$em->flush();
echo 'Success';
return true;
}
}
这是我的简单ajax请求
$('#subscribe-button').click(function() {
$.ajax({
type: 'POST',
url: '/web/app_dev.php/follow',
data: 'id={{ user.getId }}',
success: function(data){
alert(data);
}
});
});
我不想返回一些模板,这就是为什么我只返回true,但我的警报中有下一个。
成功!控制器必须返回该页面的响应(给定true)和html代码。我该怎么做才对?
不要在控制器中使用echo
,而是返回一个Response
对象:
return new Response('success');