我是 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
如果我回应($r['Attribute']['label'];)
这个值在我的 <?php ?>
中。
但不在我的 JQuery 中。
注意:
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
Error:
Name is not defined
fieldname=name;
alert(fieldname);
最佳答案
您不会考虑一旦变量得到回显,这将如何转换。
如果您有一个内容为“test”的变量 $x
,请执行以下操作:
var x = <?=$myvar?>;
将导致:
var x = test;
这是无效的(除非 test
是一个变量),因为您需要在它周围加上引号才能使其成为字符串:
var x = "<?=$myvar?>";
这会产生有效的结果:
var x = "test";
它与其他变量一起使用的原因是因为您正在回显 ID,它是一个整数:
var x = <?=$myid?>;
将翻译为:
var x = 5;
这是完全有效的。
综上所述,您应该将所有想要发送到 Javascript 的内容放入一个数组中并调用 json_encode在其上轻松安全地打印值。如果没有它,您就必须担心上面的字符串中的转义引号之类的问题。
关于php - 在 CakePHP View 中呈现 jQuery 代码时,如何使用 PHP 变量作为 <script> 标记的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/980361/