在CakePHP视图中呈现jQuery代码时,如何将PHP变量用作<script>标记的值?

use*_*non 0 javascript php jquery cakephp

我是CakePhp和JQuery的新手.我在使用JQuery中的cakephp代码时遇到错误.

我的代码

   <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 
Run Code Online (Sandbox Code Playgroud)

如果我回应($r['Attribute']['label'];)这个价值就在我的内心<?php ?>.但不是在我的JQuery中.

注意 :

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


Error: 
Name is not defined
fieldname=name; 
alert(fieldname);
Run Code Online (Sandbox Code Playgroud)

Pao*_*ino 10

一旦变量被回显,你就不会想到这是如何翻译的.

如果你有一个$x内容为"test" 的变量,那么这样做:

var x = <?=$myvar?>;
Run Code Online (Sandbox Code Playgroud)

将导致:

var x = test;
Run Code Online (Sandbox Code Playgroud)

这是无效的(除非test是变量),因为你需要在它周围引用它以使它成为一个字符串:

var x = "<?=$myvar?>";
Run Code Online (Sandbox Code Playgroud)

然后导致有效:

var x = "test";
Run Code Online (Sandbox Code Playgroud)

它与其他变量一起使用的原因是因为您正在回显一个ID,它是一个整数:

var x = <?=$myid?>;
Run Code Online (Sandbox Code Playgroud)

将翻译为:

var x = 5;
Run Code Online (Sandbox Code Playgroud)

这是完全有效的.

所有这一切,你应该将你想要发送的所有东西放到一个数组中的Javascript并调用它上面的json_encode,以便轻松安全地打印出值.没有它,你必须担心在字符串中转义引号等.