【问题标题】:Use Javascript variable in Symfony path (Ajax request) [duplicate]在 Symfony 路径中使用 Javascript 变量(Ajax 请求)[重复]
【发布时间】:2019-06-09 07:54:03
【问题描述】:

我创建了一个将数据发布到 Symfony 路径的 Ajax 请求。在我的 Symfony 路径中,我想使用 Javascript 变量来生成我的路由。

$(document).ready(function () {
            function cbOnClick(cb) {
                cbValue = cb.checked;
                todoId = cb.getAttribute('data-id');

                $.ajax({
                    url: '{{ (path('change_todo_status', {'todo_id': todoId})) }}',
                    type: "POST",
                    dataType: "json",
                    data: {
                        "status": "cbValue"
                    },
                    async: true,
                    success: function (data) {
                        console.log(data)
                    }
                });
                return false;
            }
        });

在我的 url 中,我想设置 todoId,但我收到错误,变量“todoId”不存在。

【问题讨论】:

  • 你在使用外部的JS文件,不是吗?
  • 不,它不是外部文件。这个脚本在我的树枝文件的底部
  • 与控制器参数无关。参数 (todoId) 是基于 onClick 事件的 Javascript 变量 -> todoId = cb.getAttribute('data-id');
  • 啊我没注意到。

标签: javascript jquery ajax symfony symfony4


【解决方案1】:

'{{ (path('change_todo_status', {'todo_id': todoId})) }}' 中,twig 需要一个 twig 变量。我已经遇到过这个问题,我使用了一个占位符来替换 javascript。

例如:

let todoId = cb.getAttribute('data-id');
/*
 * this will generate a path with ReplaceMeWithCorrectValue instead of the correct value.
 * You have to use a placeholder that correspond to the restrictions defined in your route.
 */
let url = "{{ (path('change_todo_status', {'todo_id': 'ReplaceMeWithCorrectValue'})) }}";

url = url.replace("ReplaceMeWithCorrectValue", todoId);

然后,在你的 ajax 中:

$.ajax({
        url: url,
   // the remain of your code

【讨论】:

  • 谢谢伙计!修复它
猜你喜欢
  • 2020-05-04
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多