如何将php变量的值传递给jquery [英] How to pass php variable's value to jquery
问题描述
我有一个php变量:
$name_of_current_page
在我的视图中可用,我想将该值提供给jquery.最好的方法是像下面这样吗?
which I have available in my view, and I want to make the value available to jquery. Is the best way to do it like the following?
$(document).ready(function () {
var current page = "<?php echo $name_of_current_page; ?>" ;
});
推荐答案
这实际上取决于您是否使用某种模板引擎.
It really depends if you are using some sort of a template engine.
-
如果您使用的是纯PHP,则唯一的选择是
echo
变量:
var current page = "<?php echo $your_var; ?>";
Twig 引擎:
var current page = "{{ your_var }}";
Smarty and RainTPL engines:
var current page = "{$your_var}";
如您所见,还有其他方法.他们都工作正常.这实际上取决于您要如何编写和组织代码.我个人使用Twig,发现它确实非常容易,快速和简单.
As you can see, there are other ways. All of them work fine. It really depends on how you'd like to write and organize your code. I personally use Twig and find it really easy,fast and straightforward.
此外,正如其他人指出的那样,您可以对服务器进行AJAX调用,并像这样获取变量.我发现该方法耗时,效率低下且不安全.如果选择此方法,则将请求发布到脚本.每个人都可以向该脚本发布/获取请求,从而为一些僵尸程序和DoS/DDoS攻击打开了大门.
Also, as others have pointed out, you can do AJAX calls to the server and fetch the variables like that. I find that method time-consuming, inefficient and insecure. If you choose this method, you will be posting requests to a script. Everybody will be able to do post/get requests to that script which opens your doors to some bots and DoS/DDoS attacks.
这篇关于如何将php变量的值传递给jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!