如何将树枝{{path('')}}调用呈现为jquery ajax url [英] how to render twig {{path('')}} call as jquery ajax url
问题描述
我正在使用来自模式框的ajax请求将数据保存在我的symfony2应用程序中.调用模态框时将渲染模态标记.因此,我不能在模态框标记中的任何地方真正使用"符号.
I am using ajax request from a modal box to save data in my symfony2 application. The modal markup is render when the modal box is called. So I cannot really use the "" signs anywhere in my modal box markup.
我的代码是:
var path = {{ path('_inserttask') }};
$.ajax({
type: 'POST',
url: path,
data: { myid: 123456 },
success: function(data) {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
}
});
当调用ajax时,它将在控制台中给出错误.我发现,如果我使用硬编码的网址-可以!但是将{{ path('_inserttask') }}
用作url会出错.我了解这是因为我没有使用引号.该如何解决呢?它已经杀死了2个小时:-(
It gives an error in the console when the ajax is called. I identified that if I use hard coded url - it works! But using {{ path('_inserttask') }}
as url gives error. I understand it is for the quote signs that I am not using. How to solve the problem? it already killed 2 hours :-(
推荐答案
根据我上面看到的内容,您尚未在path变量的值上加上双引号.试试这个-
From what I see above you haven't put double quotes on the value of the path variable. Try this -
var path = "{{ path('_inserttask') }}";
$.ajax({
type: 'POST',
url: path,
data: { myid: 123456 },
success: function(data) {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
}
});
还有更多的想法,您正在将此脚本嵌入到树枝模板中,该模板稍后将呈现为html,然后发送给浏览器,对吗?如果可以,我认为上述更改将解决此问题.
And one think more, You are embedding this script in the twig template that will later render to html and then send to the browser right? If yes the I think the above change will fix the issue.
如果您尝试在纯JavaScript文件中使用树枝.我认为这不会起作用.如果您这样做的话.我认为您尝试将路径值放在html中,然后使用javascript获取该值,然后调用ajax.例如.我会选择将该路径网址嵌入div的属性之一.
If you are trying to use twig in a pure javascript file. I don't think it will work. If you are doing this way. I think you try to put the path value in the html and then use javascript to get that value and then call the ajax instead. for example. I would choose to embedded that path url in one of attribute of a div.
在我的树枝模板文件中(例如index.html.twig)
In my twig template file (for example index.html.twig)
<div id="abc" data-path="{{path('_inserttask')}}">
</div>
在我的JavaScript文件中(例如abc.js)
In my javascript file (for example abc.js)
var path = $("#abc").attr("data-path");
$.ajax({
type: 'POST',
url: path,
data: { myid: 123456 },
success: function(data) {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
}
});
这篇关于如何将树枝{{path('')}}调用呈现为jquery ajax url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!