我在使用 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的简单ajax请求
$('#subscribe-button').click(function() {
$.ajax({
type: 'POST',
url: '/web/app_dev.php/follow',
data: 'id={{ user.getId }}',
success: function(data){
alert(data);
}
});
});
Run Code Online (Sandbox Code Playgroud)
我不想返回一些模板,这就是为什么我只是返回 true,但我正在收到警报中的下一个。
成功!控制器必须返回响应(给定 true )和该页面的 html 代码。我该怎么做才是正确的呢?
小智 6
不要echo在控制器中使用,而是返回一个Response对象:
return new Response('success');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7936 次 |
| 最近记录: |