从外部 javascript 文件访问 PHP var

发布于 2024-09-02 23:40:21 字数 499 浏览 7 评论 0原文

我可以使用 Javascript 访问 PHP var,如下所示:

<?php
    $fruit = "apple";
    $color = "red";
?>

<script type="text/javascript">
    alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>

但是如果我想使用外部 JS 文件:

<script type="text/javascript" src="externaljs.js"></script>

externaljs.js,该怎么办:

alert("color: " + "<?php echo $color; ?>");

I can access a PHP var with Javascript like this:

<?php
    $fruit = "apple";
    $color = "red";
?>

<script type="text/javascript">
    alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>

But what if I want to use an external JS file:

<script type="text/javascript" src="externaljs.js"></script>

externaljs.js:

alert("color: " + "<?php echo $color; ?>");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

云雾 2024-09-09 23:40:21

您实际上并没有访问它,而是在提供页面时将其插入到 javascript 代码中。

但是,如果您的其他 javascript 不是来自外部源,您可以执行以下操作:

<?php
    $color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>

然后在 file.js 中使用颜色,如下所示:

alert("color: " + color);

You don't really access it, you insert it into the javascript code when you serve the page.

However if your other javascript isn't from an external source you can do something like:

<?php
    $color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>

and then in the file.js use color like so:

alert("color: " + color);
趴在窗边数星星i 2024-09-09 23:40:21

您还可以从 Javascript 中的 php 脚本访问数据(这里我将使用 jQuery),如下所示

在您的 php 文件中创建输入隐藏字段,就像

<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />

在您的 javascript 文件中一样:

var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}

这也可以完成这项工作:)

You can also access data from php script in Javascript (I'll use jQuery here) like this

Create input hidden field within you php file like this

<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />

in your javascript file:

var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}

This will do the job as well :)

鹤舞 2024-09-09 23:40:21

我所看到的做法是让 .js 文件通过 php 解释器运行。 我不推荐。

我推荐的是通过 AJAX 获取值,然后让 PHP 文件将值返回到 JS 文件。这是一种更干净的方法。

What I've seen done is let .js files run through the php interpreter. Which I can not recommend.

What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.

安穩 2024-09-09 23:40:21

首先,您必须了解没有任何程序实际上可以访问其他程序的变量。

当你意识到这一点时,剩下的就很简单了。
您可以在主文件中设置一个 js 变量,然后包含您的外部 js,或者使该外部 js 动态化,也由 PHP 生成

First of all you have to understand that no program can actually have access to the other program's variable.

When you realize that, the rest is simple.
You can either set up a js variable in the main file and then include your external js, or make this external js dynamic, generated by PHP as well

子栖 2024-09-09 23:40:21

您可能想要的是异步 JavaScript 和 XML (AJAX): http://www.w3schools .com/ajax/default.aspa

基本上,想象一下能够将消息从客户端 JavaScript 发送到服务器上的 PHP 脚本。在您提供的示例 (externaljs.js) 中,您可以让脚本通过 HTTP 询问服务器 $color 是什么。您还可以将脚本标记指向生成所需 JavaScript 的 PHP 脚本。这取决于您需要做什么。

它有助于了解污染检查、数据验证和安全性;)

What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa

Basically, imagine being able to send messages from the clients JavaScript to your PHP scripts on the server. In the example you gave (externaljs.js), you would have the script ask the server what $color is, via HTTP. You can also point the script tag at a PHP script that generates the JavaScript you want. It depends on what you need to do.

It helps to have some understanding of taint checking, data verification, and security ;)

醉生梦死 2024-09-09 23:40:21

正如其他人所说,javascript 无法访问 php 变量。然而,它确实可以访问 DOM。因此,您可以使用 php 向某些页面元素添加属性。然后你可以使用 javascript 访问这些属性。

例如

完全可用于 javascript

As the others are saying, javascript doesn't have access to php variables. However, it does have access to the DOM. So, you can use php to add attributes to some page element. And then you can access those attributes with javascript.

e.g. <div id='apple' class='red'> is completely available to javascript

知你几分 2024-09-09 23:40:21

Don 解决方案很好,此外,如果您想在外部 javascipt 中使用 php 数组,这可以帮助您:

PHP:

<?php
    $my_php_array = [];
?>     

HTML:

<script type="text/javascript"> var my_js_array = <?php echo json_encode($my_php_array);?> ; </script>
<script src = "../public/js/my-external-js.js"></script>

Javasript: (您现在可以像普通的 Javascript 数组一样使用该数组)

 my_js_array[0] 
 my_js_array.length

Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you:

PHP:

<?php
    $my_php_array = [];
?>     

HTML:

<script type="text/javascript"> var my_js_array = <?php echo json_encode($my_php_array);?> ; </script>
<script src = "../public/js/my-external-js.js"></script>

Javasript: (You can now use the array like a normal Javascript array)

 my_js_array[0] 
 my_js_array.length
自我难过 2024-09-09 23:40:21

externaljs.js 是一个静态文件。当然它不能访问PHP数据。将 PHP 数据传递到 js 文件的唯一方法是通过在 PHP 脚本中写入来物理更改该文件,尽管这充其量是一个混乱的解决方案。

编辑以回应 Ólafur Waage 的回答:我想写入 js 文件并不是唯一的方法。我从来没有想过通过 PHP 解释器传递 js(有充分的理由)。

externaljs.js is a static file. Of course it can't access PHP data. The only way to pass PHP data to a js file would be to physically alter the file by writing to it in your PHP script, although this is a messy solution at best.

Edit in response to Ólafur Waage's answer: I guess writing to the js file isn't the only way. Passing the js through the PHP interpreter never crossed my mind (for good reason).

GRAY°灰色天空 2024-09-09 23:40:21
<script type="text/javascript" src="externaljs.js"></script>

你可以将其更改为

<script type="text/javascript" src="externaljs.php"></script>

PHP 脚本可以像这样编写 JavaScript :

<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...

虽然像 Sepehr Lajevardi 那样使用 AJAX 会更干净

<script type="text/javascript" src="externaljs.js"></script>

You could change it to

<script type="text/javascript" src="externaljs.php"></script>

And the PHP script could just write JavaScript like that :

<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...

Though using AJAX like said Sepehr Lajevardi would be much cleaner

So要识趣 2024-09-09 23:40:21

2017-2018及以上解决方案:

由于还没有人提出它,而且我猜还没人想到将函数 base64_encodejson_encode 结合起来,你甚至可以像这样发送 PHP 数组变量:

index.php

<?php
      $string = "hello";
      $array = ['hi', 'how', 'are', 'you'];
      $array = base64_encode(json_encode($array));

然后,您可以使用查询字符串的参数加载所需的 js 文件,如下所示:

echo '

那么 js/main.php 将如下所示。您可以这样测试您的变量:

js/main.php

    <?php
    if ($_GET['string']) {
        $a = $_GET['string'];
    }
    if ($_GET['array']) {
        $b = $_GET['array'];
    }
    $b = json_decode(base64_decode($b));

    echo 'alert("String $a: + '.$a.'");';
    echo 'alert("First key of Array $array: + '.$b[0].'");';
    exit();
    ?>

当您打开 index.php 时,将输出以下内容。所以你看,你没有打开 js/main.php ,你仍然可以从中获得 javascript 功能。

输入图片此处描述

2017-2018 and above solution:

Since nobody bringed it up yet and I guess no one thought of combining the functions base64_encode and json_encode yet, you could even send PHP Array variables like that:

index.php

<?php
      $string = "hello";
      $array = ['hi', 'how', 'are', 'you'];
      $array = base64_encode(json_encode($array));

Then you could just load your desired js file with the parameter for a query string like this:

echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';

Then js/main.php will look like this for example. You can test your variables this way:

js/main.php

    <?php
    if ($_GET['string']) {
        $a = $_GET['string'];
    }
    if ($_GET['array']) {
        $b = $_GET['array'];
    }
    $b = json_decode(base64_decode($b));

    echo 'alert("String $a: + '.$a.'");';
    echo 'alert("First key of Array $array: + '.$b[0].'");';
    exit();
    ?>

The following will then output when you open your index.php. So you see, you don't open js/main.php and you still got the javascript functionality from it.

enter image description here

余罪 2024-09-09 23:40:21

您可以像使用其他任何东西一样 include() 它们:

<?php
    $fruit = "apple";
    $color = "red";
?>

<script type="text/javascript">
    <?php include('/path/to/your/externaljs.js'); ?>
</script>

这基本上会将外部文件渲染为内联 js。这里的主要缺点是您失去了浏览器缓存的潜在性能优势。另一方面,它比在 javascript 中重新声明 php 变量要容易得多。

You can include() them just as you would anything else:

<?php
    $fruit = "apple";
    $color = "red";
?>

<script type="text/javascript">
    <?php include('/path/to/your/externaljs.js'); ?>
</script>

This will basically render the external file as inline js. The main disadvantage here is that you lose the potential performance benefit of browser caching. On the other hand, it's much easier than re-declaring your php variables in javascript.

薔薇婲 2024-09-09 23:40:21

你不能这样做,也不要尝试这样做,因为这不是推荐的方法,但是你可以将 php 变量作为函数参数传递给用外部 js 编写的函数

You cant do that and dont try to as this is not a recommended approach, However you can pass php variables as a function parameters to function written in external js

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文