How to access smarty variable and assign to jquery

2019-08-18 03:20发布

问题:

I just need your help about my code. My problem is how can I access smarty variable within jquery or javascript file? Becuase my smarty variable is a URL request from my controller. And I need to use that variable for creating validation. Here's my code.

{$get.search_by} {**works without error**}

{literal}
    <script type="text/javascript">

        $(document).ready(function(){

            var dispatch = "{$get.search_by}"; //can't access

            var new_class = "it3 ir3 il3 jt10 jr05 jl05 kt03 kr04 kl04";
            var old_class = "it3 ib3 il3 jt05 jb05 jl10 kt04 kb04 kl03";

            var toggleState = true;

            //could not access
            if(dispatch == companies.catalog){
                alert("catalog");
            }else{
                alert("product search");
            }

            console.log(dispatch);

回答1:

Try this code

var dispatch = '{/literal}{$get.search_by}{literal}'


回答2:

To make things cleaner, you can move the {literal} tag down and also escape the $get.search_by variable (in case search_by may have a string with a quote i.e. "let's try"):

<script type="text/javascript">
var dispatch = '{$get.search_by|escape:'javascript'}';

{literal}