我正在寻找一种更好的方法来将PHP变量发送到Javascript。目前我在PHP中回显该变量:
<script>
var numbers = <?php echo $numbers ?>;
</script>
然后我在Javascript中访问这个变量,如下所示:class.method(numbers);
我的PHP文件包含在index.php中,在javascript文件之前,所以我可以访问javascript文件中的这个变量。
现在我正在寻找一种比使用echo
更好的方法来提交PHP变量。有人有主意吗?
数字的输出如下所示:
5条答案
按热度按时间vxqlmq5t1#
如果你想把你的php和JS混在一起.你用过的那个更好.你也可以试试这样的方法在你的html页面上添加一个不显示的span,id:document_target example
在js文件中获取带有id的span数据
mwecs4sa2#
以下是一种可行的方法:
1.如果有表单,从表单字段中获取值,或者其他什么,然后通过查询从JS发送到php,无论php文件在哪里,它都可以工作,它可以是不同服务器上的远程文件,或者只是另一个本地页面,等等。
1.获取JS中php文件的回复。
上面使用jquery的一个例子:
现在,在php文件中,您需要使文件在收到包含上面提到的
some_requestPHP_name
行的内容时做出React,这是您决定的参数根据您的使用情况,您可能没有表单/按钮等,因此您可能希望删除.change()并立即执行该函数,此时您可以根据需要调整示例。
fv2wmkja3#
您可以使用内联脚本标记向HTML文档添加数据,如下所示:
可以看出,运行该示例时,JS类型属性不合适的脚本没有执行。
在该脚本标记中,您可以根据需要回显变量或其他值(就像后面的例子),或者甚至回显一个
json_encode
d字符串。这是将PHP变量包含到JS中最安全的方法之一,并且您仍然可以将实际JavaScript保存到外部文件中。数据脚本必须包含在HTML文档中,因为您无法使用PHP访问. js文件,并且出于安全原因,JS无法从外部文件读取text
。至于
echo
的用法,它是一个PHP语言构造,专门用于向标记添加内容,没有理由避免它。在后一个示例中,我使用了echo
的简写,但它仍然是echo
。hfsqlsce4#
一个更好的替代方法是将PHP值输出到
data
属性中,假设这个变量似乎没有绑定到特定的元素,可以将它放在body
元素的根级别,然后在加载DOM后执行JS时可以从那里读取它,如下所示:这是在假设PHP中的
$numbers
变量持有一个可以强制转换为字符串的值的情况下进行的考虑到您对问题的编辑,您澄清了
$numbers
实际上包含一个对象,您可以将其编码为JSON,输出到<script>
标记,然后从那里使用它:一个二个一个一个
e4eetjau5#
我是这样做的:
看,
onClick='returnValues(".$x.");'
在它自己里面有来自PHP的变量。所以你要用函数把variable给javascript。现在你可能知道了:现在你可以很好,当你有任何其他问题,随时问:D祝你有美好的一天!