Use js variables in twig and js variables in twig

Source: Internet
Author: User

Use js variables in twig and js variables in twig

This article describes how to use js variables in twig. We will share this with you for your reference. The details are as follows:

First read a piece of code

<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>

The address of this ajax request cannot be accessed normally.

In this Code, the value of jQuery ("# my_input"). val () is assigned to the value, and then you want to introduce the value variable to the url address in ajax.

At this time, you will find that the value of the address you access is not introduced, but is processed as a string.

That is to say, the js value cannot be directly referenced in twig.

The reason is that twig parses php variables while value is js variables, so twig is considered a string by default.

Therefore, replace must be used for replacement.

The Code is as follows. You can compare it with the above Code:

<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>

Permanent address: http://blog.it985.com/7020.html
This article is from the IT985 blog. Please indicate the source and relevant links when reprinting.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.