简体   繁体   English

如何将声明的PHP变量作为jQuery选择器获取?

[英]How to grab a declared PHP variable as jQuery selector?

I cannot figure out how to grab a PHP variable and use it as a jQuery variable. 我无法弄清楚如何获取PHP变量并将其用作jQuery变量。

So, I've got for example this variable: 所以,我有这个变量的例子:

$content = "bla bla bla"; $ content =“bla bla bla”;

And it is inside a DIV: 它在DIV中:

div id='contentWrapper' div id ='contentWrapper'

$content = "bla bla bla"; $ content =“bla bla bla”;

/div / DIV

I know how to grab the ID, class and content (text) of the DIV contentWrapper, but how do I grab $content? 我知道如何获取DIV contentWrapper的ID,类和内容(文本),但我如何获取$ content? I hope I am being clear enough :) 我希望我足够清楚:)

You can't. 你不能。 The PHP runs on the server. PHP在服务器上运行。 The output of the PHP gets sent to the browser. PHP的输出被发送到浏览器。 JavaScript runs in the browser. JavaScript在浏览器中运行。 JavaScript has no access to the internals of the script that generated the page it is running in. JavaScript无法访问生成其运行页面的脚本的内部。

You would have to modify the PHP to output the information you want to make available to JS so that it appears in the page. 您必须修改PHP以输出您想要提供给JS的信息,以便它出现在页面中。

In the javascript, you can do: 在javascript中,您可以执行以下操作:

Edit: 编辑:

Based on @Marc B's comment. 基于@Marc B的评论。

var jsvar = <?php echo json_encode($content); ?>

According to what I believe PHP is server side scripting which is hidden from browser and Jquery script is executed by browser. 据我所知,PHP是浏览器隐藏的服务器端脚本,浏览器执行Jquery脚本。 So to obtain the variable value you need to echo and show your content to browser to complete JQuery. 因此,要获取变量值,您需要回显并向浏览器显示您的内容以完成JQuery。 Use the method provided by Jonathan Sampson 使用Jonathan Sampson提供的方法

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

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