是否可以在javascript中传递php变量? [英] Is it possible to pass a php variable inside javascript?

查看:50
本文介绍了是否可以在javascript中传递php变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在javascript中传递一个php变量但是它无效。

I am trying to pass a php variable inside javascript bt it is not working.

<a href="javascript:wait1();getPass('<?php echo $current?>');">Comment</a>

是否可以这样做或者我可能在某处错误...

Is it possible to do so or I may be incorrect somewhere...

感谢您的回复! :)

推荐答案

您正在动态生成Javascript。如果你需要这样做的话,你会省去一些麻烦,保持简单。在页面顶部以最简单的方式将数据从PHP传输到Javascript:

You're dynamically generating Javascript. You will save yourself some headaches if when you need to do this you, keep it simple. Transfer the data from PHP to Javascript in the simplest way possible at the top of the page:

<script type="text/javascript" >
var $current = '<%? echo $current; %>';
</script>

正如其他人所指出的那样,你需要使用 json_encode (如果你知道可能的值,你可能不需要引号),或者更简单的转义函数。

As others have pointed out, you will want to encode and quote your php variable, using json_encode (in which case you probably won't need the quotes), or a simpler escape function if you know the possible values.

现在,你的内联代码可以更简单:

Now, your inline code can be simpler:

<a href="javascript:wait1();getPass($current);">Comment</a>

最后的建议是将其拉出到自己的函数中,然后使用onclick属性。

A final recommendation would be to pull this out into its own function, and use the "onclick" attribute.

这篇关于是否可以在javascript中传递php变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆