【问题标题】:Symfony - How to use JavaScript variable to be a parameter value in Symfony route?Symfony - 如何使用 JavaScript 变量作为 Symfony 路由中的参数值?
【发布时间】: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


    【解决方案1】:

    如何将url 作为每行的data 属性传递并在js 中收集。这样您就不必在 javascript 中构建 url

    <button class="btn btn-danger waves-effect" data-type="delete-user" id="{{ user.id }}" data-href="{{ path('fos_user_deleteUser', { 'id': user.id }) }}">
        <i class="material-icons">delete_forever</i>
    </button>
    

    在 twig 中,添加 js 之前:

    <script type="text/javascript">
        var user_list_url = "{{ path('route_to_user_listing') }}";
    </script>
    

    为什么需要上面的代码? 所以:

    • 您的路由中对 url 路径 /users 的任何更改都会受到尊重。
    • 从子文件夹加载您的网站时,/ 可能会很棘手。

    然后,在 javascript 中收集相应的 url。

    $(function () {
            $('.js-sweetalert button').on('click', function () {
                var type = $(this).data('type');
                if (type === 'delete-user') {
                    var userId = $(this).attr('id'); // you might need an id somewhere.
                    var deleteUrl = $(this).data('href');
                    showDeleteUserMessage(userId, deleteUrl);
                }
            });
        });
        function showDeleteUserMessage(userId, deleteUrl) {
            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: deleteUrl,
                        success: function() {
                            swal("Success", "The user has been removed from the Database!", "success");
                            window.location.href = user_list_url;
                        }
                    });
                } else {}
            });
        }
    

    对我来说它总是有效的。

    希望对你有帮助!

    【讨论】:

    • 它成功删除了目标用户,与我发布的解决方案相同,我在路由中手动输入了用户 ID,但仍然没有将页面重新加载到新更新的用户表中我页面中的一些下拉按钮现在无法使用。你能改进你的代码吗?
    • 要重新加载页面,您只需在 javascript 中添加 location.hrefwindow.location.href(代码已更新)。要解决您的下拉问题,您必须从 console 对其进行调试,看看那里有什么 JS 错误。
    • 我就是这么做的。现在,我将它转移到它自己的外部脚本 (mySweetAlert.js)。它现在不影响其他下拉按钮,但仍然没有解决在没有删除用户的情况下不将页面重新加载到新更新的用户表的问题。
    • 你整合window.location.href了吗?如果你这样做了,在你点击删除按钮之前,你是否在页面的源代码中看到了正确的重新加载路径?
    • 我尝试了location.hrefwindow.location.href 但它返回了这个错误,No route found for "GET /%7B%7B%20path('fos_user_userList')%20%7D%7D" (from "http://localhost:8000/users")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 2022-10-05
    相关资源
    最近更新 更多