在 Symfony 路径中使用 Javascript 变量(Ajax 请求)
Use Javascript variable in Symfony path (Ajax request)
我创建了一个 Ajax 请求将数据发布到 Symfony 路径。在我的 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" 不存在。
在 '{{ (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
我创建了一个 Ajax 请求将数据发布到 Symfony 路径。在我的 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" 不存在。
在 '{{ (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