Using JavaScript variables in twig

Source: Internet
Author: User

First read a piece of code

The code is as follows: Copy 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 ', {'ergencia': 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 you want to introduce the value variable
In 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:

 

The code is as follows: Copy 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 ', {'ergencia': 'text '})}}";
Url = url. replace ("text", value );
 
JQuery. ajax ({
 
Url: url,
Timeout: 5000,
Success: function (data ){
Alert ('OK ');
},
Error: function (){
Alert ('mal ');
                }
});
 
});
 
});
</Script>
Related Article

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.