【发布时间】:2015-08-10 00:02:30
【问题描述】:
我有一个非常简单的系统,普通用户,黄金用户。起初它只是简单地在 routing.yml 中创建了一个路径,我将函数寻址到执行操作并返回相同的视图并完美运行。现在实现 ajax 以加快进程。 当我点击按钮向上时,运行Ajax,控制器的指定路径将我引导至相关动作,全部成功执行,但在返回同一视图时,无法正常工作。 Ajax 采取错误路径,并由我编写的警报屏幕打印。总之,一切正常,直到我不得不返回 Ajax 操作。
listarUsuariosParaAscender.html.twig
//..some code..//
<p id="{{ usuario.id }}" >Ascender a Usuario Gold</p>
//..some code..//
{% block javascripts %}
{{ parent() }}
<script type="text/javascript" src=" {{ asset('bundles/MICARPETA/js/jquery-2.1.4.min.js') }} "></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("p").click(function(e){
var id = $(this).attr('id');
$.ajax({
type: "POST",
url: "{{ path('ascender_a_gold') }}",
data: { 'id' : ' ' + id + ' ' },
error: function(){
alert("Error petición ajax");
},
success: function(data){
alert(data);
}
});
});
});
</script>
{% endblock %}
routing.yml
ascender_a_gold:
pattern: /admin/ascenderAGold
defaults: { _controller: ProyectoAdminBundle:Admin:ascenderAGold }
AdminController.php
public function ascenderAGoldAction(){
$id = $_POST['id'];
$em = $this->getDoctrine()->getManager();
$user = new User();
$roleviejo = new Role();
$rolenuevo = new Role();
$usuario = $em->getRepository('AtajoBundle:User')->findOneUser($id);
$roleviejo = $em->getRepository('ProyectoSeguridadBundle:Role')->findByRoleJoinUsuario($id);
$rolenuevo = $em->getRepository('ProyectoSeguridadBundle:Role')->findByRole('ROLE_USER_GOLD');
$usuario->setRoles($rolenuevo);
$em->persist($usuario);
$em->flush();
//Until here everything works well , when I have to return to Ajax , ajax it takes the path of 'error'
$data = 'hello';
return new JsonResponse(array('data' => $data));
}
【问题讨论】:
-
检查浏览器开发工具网络中的实际请求以查看状态和返回的内容(如果有)。还为`$.ajax 设置
dataType:'json' -
你为什么使用
$_POST而不是symfony的Request对象?
标签: javascript php jquery ajax symfony