【发布时间】:2017-09-20 05:45:07
【问题描述】:
注意:由于我们公司的限制,我无法安装 FOSJsRoutingBundle。
场景:我有一个 Twig 模板,它在我的数据库中显示了一个注册用户表。有对应于每个用户的按钮。每个按钮都有更新和删除用户的功能。我现在正在处理删除用户按钮。
问题: 我的问题是,如何在 Symfony 路由中使用 JavaScript 变量作为参数值? 例如
这条路径: {{ path('route_to_deleteUser', { 'id': user.id }) }}
在 Ajax 中更改为这个示例路径:
var userId = $(this).attr('id');
var route = "{{ path('route_to_deleteUser', { 'id': userId }) }}";
我试过了,但它什么也没做。我也试过这样做:
var route = "{{ path('route_to_deleteUser', { 'id': 10 }) }}"; // 10 is the value of user with id = 10
上面的代码成功删除了 id = 10 的用户,但它只删除了我在路径中手动输入的 id,而且它只显示 SWAL 成功消息,但没有重新加载页面以显示新用户表被删除的用户。
目标:我想要一个按钮,为我的 deleteUser 函数执行 SWAL 确认消息,并在成功消息后返回带有更新数据库的新用户表。
这是我的路线:
fos_user_deleteUser:
path: /users/{id}
defaults: { _controller: FOSUserBundle:Profile:deleteUser }
这是我的控制器:
public function deleteUserAction($id)
{
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(['id' => $id]);
if ($user == null) {
throw new NotFoundHttpException('User not found for user' . $user);
}
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
$userManager->deleteUser($user);
$this->setFlash('user_deleted', $user . ' has been successfully deleted!');
$url = $this->generateUrl('fos_user_userList');
return new RedirectResponse($url);
}
这是我的树枝:
<tbody>
{% for user in user %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.username }}</td>
<td>{{ user.email }}</td>
<td>{{ user.roles[0] }}</td>
<td>{{ user.lastLogin | date('F m, Y') }}</td>
<td class="row clearfix js-sweetalert">
{% if is_granted('ROLE_ADMIN') %}
<center>
<div class="btn-group" role="group">
<button class="btn btn-warning waves-effect" data-type="update-user"><i class="material-icons">supervisor_account</i></button>
<button class="btn btn-danger waves-effect" data-type="delete-user" id="{{ user.id }}"><i class="material-icons">delete_forever</i></button>
</div>
</center>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
这是我的脚本:
<script>
$(function () {
$('.js-sweetalert button').on('click', function () {
var type = $(this).data('type');
if (type === 'delete-user') {
var userId = $(this).attr('id');
showDeleteUserMessage();
}
});
});
function showDeleteUserMessage(userId) {
swal({
title: "Delete this user?",
text: "You will not be able to recover this user",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#dd6b55",
confirmButtonText: "Delete",
closeOnConfirm: false
}, function (isConfirm) {
if (isConfirm) {
$.ajax({
type: 'POST',
url: "{{ path('fos_user_deleteUser', { 'id': userId }) }}",
success: function() {
swal("Success", "The user has been removed from the Database!", "success");
}
});
} else {}
});
}
</script>
随时编辑问题和内容以进行更正。
我希望有人可以帮助我,并在被问到时回复。我之前的问题没有回复。
【问题讨论】:
标签: javascript php ajax symfony