How do I use PHP variables as values for the [removed] tag when rendering jQuery code in my CakePHP view?

后端 未结 1 891
说谎
说谎 2021-01-27 05:56

I m new to CakePhp and JQuery. I am getting an error in using the cakephp code inside my JQuery.

My code

   

        
相关标签:
1条回答
  • 2021-01-27 06:11

    You are not thinking about how this is translating over once the variables are echoed.

    If you have a variable $x with the contents "test", doing this:

    var x = <?=$myvar?>;
    

    Will result in:

    var x = test;
    

    This is not valid (unless test is a variable) because you need quotations around it to make it a string:

    var x = "<?=$myvar?>";
    

    Which then results in the valid:

    var x = "test";
    

    The reason it works with the other variable is because you are echoing an ID, which is an integer:

    var x = <?=$myid?>;
    

    Would translate to:

    var x = 5;
    

    Which is perfectly valid.

    All this being said, you should put all the stuff you want to send over to Javascript in an array and call json_encode on it to easily and safely print the values over. Without it, you have to worry above about escaping quotes in the string and such.

    0 讨论(0)
提交回复
热议问题