简体   繁体   English

如何使用PHP变量作为<script> tag when rendering jQuery code in my CakePHP view?

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

I m new to CakePhp and JQuery. 我是CakePhp和JQuery的新手。 I am getting an error in using the cakephp code inside my JQuery. 我在JQuery中使用cakephp代码时遇到错误。

My code 我的密码

   <script type="text/javascript">
     $(document).ready(function(){
     var attributeid;var fieldname;
     $("#"+<?=$r['Attribute']['id'];?>).change(function () {

     fieldname=<?=$r['Attribute']['label'];?>; 
              alert(fieldname);//this show me that undefined 
             attributeid=<?=$r['Attribute']['id'];?>; 
             alert(attributeid);//But this works

    });//attribute change
});//ready function 

if I echoed ($r['Attribute']['label'];) this value is coming inside my <?php ?> . 如果我回显了($r['Attribute']['label'];)此值在我的<?php ?> But not inside my JQuery. 但不在我的JQuery内部。

Note : 注意 :

attributeid=<?=$r['Attribute']['id'];?>; 
alert(attributeid);//But this works  


Error: 
Name is not defined
fieldname=name; 
alert(fieldname);

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: 如果您的变量$x的内容为“ test”,请执行以下操作:

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: 这是无效的(除非test是变量),因为您需要在其周围引号使它成为字符串:

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: 它与其他变量一起使用的原因是因为您正在回显一个ID,它是一个整数:

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. 综上所述,您应该将要发送到Javascript的所有内容放入一个数组中,并在其上调用json_encode ,以轻松安全地打印这些值。 Without it, you have to worry above about escaping quotes in the string and such. 没有它,您就不得不担心在字符串等中转义引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM