简体   繁体   English

从 PHP 获取变量并在 javascript 上使用它

[英]Get variable from PHP and use it on javascript

I googled about it and didn't find an solution, can you help me with this issue?我用谷歌搜索并没有找到解决方案,你能帮我解决这个问题吗?

I have a javascript variable that is the name of a php session address, and I want to use this session value in my javascript code, but I don't know how to pass this name to the php and return the session value to my js code.我有一个 javascript 变量,它是 php 会话地址的名称,我想在我的 javascript 代码中使用此会话值,但我不知道如何将此名称传递给 php 并将会话值返回给我的 js代码。

I'm using the session to set values of my dynamic form fields.我正在使用会话来设置动态表单字段的值。 So I use所以我用

var field_name = "field";    
document.getElementById(field_name).value = "<?php if(isset($_SESSION['field_name'])) echo $_SESSION['field_name'];?>";

The field ID have the same name of the session address.字段 ID 具有与会话地址相同的名称。 I can't simply use the word "field" because it's dynamic.我不能简单地使用“字段”这个词,因为它是动态的。

I thank you in advance.我提前谢谢你。

只需使用:

var info= <?php echo json_encode("some_php_variable_here", JSON_HEX_TAG); ?>;

This is probably only with a data attribute in the HTML.这可能仅适用于 HTML 中的数据属性。 In the JS code one should definitely (actually never) run PHP code.在 JS 代码中,绝对应该(实际上永远不会)运行 PHP 代码。

The data attributes can then be filled with PHP and read out in the JS.然后可以用 PHP 填充数据属性并在 JS 中读出。

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

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