树枝模板内的变量jquery [英] variable jquery inside twig template

查看:21
本文介绍了树枝模板内的变量jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在树枝模板中使用 jquery 变量以通过 ajax 发送,但我无法访问树枝内的 jquery 变量:

I'm trying to use a jquery varaible inside a twig template to send by ajax, but I can't access to the jquery variable inside the twig:

我的代码是:

<script type="text/javascript">
            jQuery(document).ready(function(){


                jQuery("#my_input").change(function(){

                    var value = jQuery("#my_input").val();

                    jQuery.ajax({

                        url: "{{ path('ParteAccidentes_ajax', {'emergencia': value}) }}",
                        timeout: 5000,
                        success: function(data) { 
                           alert('ok');
                        },
                        error: function() { 
                            alert('mal');
                        }
                    });

                });

            });  
        </script>

错误显示变量值不存在(在url:..."行)

The error show is variable value doesn't exist (in "url:..." line)

谢谢!

推荐答案

问题是 Twig 比 JavaScript 更早启动,Twig 无法识别变量id_emergencia".你可以做一个小把戏.您可以将字符串作为参数,然后在 JavaScript 代码中,将字符串替换为变量的值.这样,在启动 AJAX 请求之前,您将始终拥有正确的 url.

The problem is that Twig is launched before than JavaScript and the variable "id_emergencia" is not recognized by Twig. You could do a trick. You can put a string, as a parameter and then, in the JavaScript code, you replace the string with the value of your variable. In this way, you will always have the correct url before your AJAX petition is launched.

你可以这样做:

<script type="text/javascript">
            jQuery(document).ready(function(){

                jQuery("#my_input").change(function(){
                    
                    var value = jQuery("#my_input").val();
                    var url = "{{ path('ParteAccidentes_ajax', {'emergencia': 'text'}) }}";
                    url = url.replace("text", value);
                                        
                    jQuery.ajax({
                        
                        url: url,
                        timeout: 5000,
                        success: function(data) { 
                           alert ('ok');
                        },
                        error: function() { alert ('mal');
                        }
                    });

                });

            });  
        </script>

这篇关于树枝模板内的变量jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆