【问题标题】:Symfony Controller should return responseSymfony 控制器应该返回响应
【发布时间】:2016-01-30 01:05:40
【问题描述】:

我在使用 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 代码。我该怎么做才对?

【问题讨论】:

  • 强调:控制器必须return响应

标签: php ajax symfony


【解决方案1】:

不要在控制器中使用echo,而是返回一个Response对象:

return new Response('success');

【讨论】:

    猜你喜欢
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多