如何将PHP变量赋予Javascript? [英] How to give PHP variable to Javascript?

查看:40
本文介绍了如何将PHP变量赋予Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将PHP变量发送到Javascript的更好方法.目前,我在PHP中回显了变量:

 < script>var number =<?php echo $ numbers?> ;;</script> 

然后我使用如下代码在Javascript中访问此变量: class.method(numbers);

我的PHP文件包含在javascript文件之前的index.php中,因此我可以访问javascript文件中的此变量.

现在,我正在寻找一种比使用 echo 更好的提交PHP变量的方法.有人有主意吗?

数字输出如下:

解决方案

您可以使用内联脚本标签将数据添加到HTML文档中,如下所示:

  const dataElement = document.querySelector('#phpData'),数据= JSON.parse(dataElement.text);console.log(data.example,data.number);  

 < script type ="text/plain" id ="phpData">{"example":示例字符串",数字":10}</script>< script type ="text/plain">{"someValue":<?= $ some_value?> ;,"otherValue":<?= $ other_value?>}</script>  

可以看出,在运行示例时,不执行具有不正确的JS type属性的脚本.

在该脚本标签中,您可以根据需要回显变量或其他值(如后面的示例中所示),甚至回显 json_encode d字符串.这是将PHP变量包含到JS中的最安全的方法之一,您仍然可以将实际的JavaScript保存到外部文件中.数据脚本必须包含在HTML文档中,因为您无法使用PHP访问.js文件,并且出于安全原因,JS无法从外部文件读取 text .

echo 的用法是什么,它是一种PHP语言结构,专门用于向标记添加内容,没有理由避免使用它.我使用了 echo 的简写在后面的示例中是a>,但仍然是 echo .

I am searching for a better way to send my PHP variable to Javascript. Currently I echo the variable in PHP:

<script>
  var numbers = <?php echo $numbers ?>;
</script>

I then access this variable in Javascript like this: class.method(numbers);

My PHP file is included in the index.php before the javascript file, so I have access to this variable in the javascript file.

Now I am looking for a nicer way to submit the PHP variable than using echo. Does anyone have an idea?

The output of numbers looks like:

解决方案

You can use an inline script tag to add data to the HTML document like this:

const dataElement = document.querySelector('#phpData'),
  data = JSON.parse(dataElement.text);
  
console.log(data.example, data.number);

<script type="text/plain" id="phpData">
{
  "example": "Example string",
  "number": 10
}
</script>

<script type="text/plain">
{
  "someValue": <?=$some_value?>,
  "otherValue": <?=$other_value?>
}
</script>

As can be seen, when running the example, the script with inappropriate JS type attribute is not executed.

In that script tag you can echo variables or other values as you need (like in the latter example), or even echo a json_encoded string. This is one of the safest way to include PHP variables to JS, and you can still save your actual JavaScript into an external file. The data script must be included in the HTML document, because you can't access .js files with PHP, and also, for security reasons, JS can't read text from an external file.

What comes to the usage of echo, it's a PHP language construct specifically meant to add content to the markup, there's no reason to avoid it. I've used a short hand of echo in the latter example, but it still is echo.

这篇关于如何将PHP变量赋予Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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