简体   繁体   English

从外部javascript文件访问PHP var

[英]Access PHP var from external javascript file

I can access a PHP var with Javascript like this: 我可以使用Javascript访问PHP var,如下所示:

<?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: 但是如果我想使用外部JS文件怎么办:

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

externaljs.js: externaljs.js:

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

You don't really access it, you insert it into the javascript code when you serve the page. 您没有真正访问它,在您提供页面时将其插入到javascript代码中。

However if your other javascript isn't from an external source you can do something like: 但是,如果您的其他JavaScript不是来自外部来源,您可以执行以下操作:

<?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: 然后在file.js中使用颜色如下:

alert("color: " + color);

You can also access data from php script in Javascript (I'll use jQuery here) like this 您也可以在Javascript(我将在这里使用jQuery)中从PHP脚本访问数据

Create input hidden field within you php file like this 像这样在你的php文件中创建输入隐藏字段

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

in your javascript file: 在您的javascript文件中:

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 :) 这也将完成这项工作:)

What I've seen done is let .js files run through the php interpreter. 我所看到的是让.js文件通过php解释器运行。 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. 我建议通过AJAX获取值并让PHP文件将值返回给JS文件。 Which is a much cleaner method. 这是一种更清洁的方法。

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 您可以在主文件中设置一个js变量,然后包含外部js,或者使这个外部js动态化,由PHP生成

What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa 您可能想要的,称为异步JavaScript和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. 基本上,想象一下能够将客户端JavaScript中的消息发送到服务器上的PHP脚本。 In the example you gave (externaljs.js), you would have the script ask the server what $color is, via HTTP. 在你给出的例子(externaljs.js)中,你会让脚本通过HTTP向服务器询问$ color是什么。 You can also point the script tag at a PHP script that generates the JavaScript you want. 您还可以将脚本标记指向生成所需JavaScript的PHP脚本。 It depends on what you need to do. 这取决于你需要做什么。

It helps to have some understanding of taint checking, data verification, and security ;) 它有助于对污点检查,数据验证和安全性有所了解;)

As the others are saying, javascript doesn't have access to php variables. 正如其他人所说,javascript无法访问php变量。 However, it does have access to the DOM. 但是,它确实可以访问DOM。 So, you can use php to add attributes to some page element. 因此,您可以使用php将属性添加到某个页面元素。 And then you can access those attributes with javascript. 然后你可以使用javascript访问这些属性。

eg <div id='apple' class='red'> is completely available to javascript 例如<div id='apple' class='red'>完全可用于javascript

externaljs.js is a static file. externaljs.js是一个静态文件。 Of course it can't access PHP data. 当然它无法访问PHP数据。 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. 将PHP数据传递给js文件的唯一方法是通过在PHP脚本中写入来物理地改变文件,尽管这是一个混乱的解决方案。

Edit in response to Ólafur Waage's answer: I guess writing to the js file isn't the only way. 编辑以回应ÓlafurWaage的回答:我想写入js文件不是唯一的方法。 Passing the js through the PHP interpreter never crossed my mind (for good reason). 通过PHP解释器传递js永远不会超出我的想法(有充分的理由)。

<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脚本可以像这样编写JavaScript:

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

Though using AJAX like said Sepehr Lajevardi would be much cleaner 虽然像说Sepehr Lajevardi那样使用AJAX会更加清洁

Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you: Don解决方案很好,而且如果你想在外部javascipt中使用php数组,这可以帮助你:

PHP: PHP:

<?php
    $my_php_array = [];
?>     

HTML: 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) Javasript :(你现在可以像普通的Javascript数组一样使用数组)

 my_js_array[0] 
 my_js_array.length

2017-2018 and above solution: 2017-2018及以上解决方案:

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: 既然没人知道它,我想没有人想到将函数base64_encodejson_encode结合起来,你甚至可以像这样发送PHP数组变量:

index.php 的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: 然后你可以加载你想要的js文件和查询字符串的参数,如下所示:

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

Then js/main.php will look like this for example. 然后js/main.php看起来像这样。 You can test your variables this way: 您可以这样测试变量:

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();
    ?>

The following will then output when you open your index.php . 打开index.php时,将输出以下内容。 So you see, you don't open js/main.php and you still got the javascript functionality from it. 所以你看,你没有打开js/main.php ,你仍然可以从中获得javascript功能。

在此输入图像描述

你不能这样做,不要尝试,因为这不是一个推荐的方法,但你可以传递PHP变量作为函数参数写入外部js函数

You can include() them just as you would anything else: 你可以像其他任何东西一样include()它们:

<?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. 这将基本上将外部文件呈现为内联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. 另一方面,它比在javascript中重新声明你的php变量容易得多。

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

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