我在使用 symfony Controller 时遇到一些问题,为什么要发送 ajax 请求。
这是我的 Controller
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,但我会在我的警报中得到下一个。
成功了! Controller 必须返回响应(给定的真值)和该页面的 html 代码。我应该怎么做才正确?
最佳答案
不要在 Controller 中使用 echo
而是返回一个 Response
对象:
return new Response('success');
关于php - Symfony Controller 应该返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33421869/