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

查看:91
本文介绍了树枝模板内的可变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请求之前,您将始终拥有正确的网址.

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天全站免登陆