我有一个变量在PHP,我需要它的值在我的JavaScript代码。我怎么能把我的变量从PHP到JavaScript?

我有这样的代码:

<?php
$val = $myService->getValue(); // Makes an API and database call

在同一页上,我有JavaScript代码,需要$val变量的值作为参数传递:

<script>
    myPlugin.start($val); // I tried this, but it didn't work
    <?php myPlugin.start($val); ?> // This didn't work either
    myPlugin.start(<?=$val?>); // This works sometimes, but sometimes it fails
</script>

当前回答

只需使用以下方法之一。

<script type="text/javascript">
var js_variable  = '<?php echo $php_variable;?>';
<script>

OR

<script type="text/javascript">
    var js_variable = <?php echo json_encode($php_variable); ?>; 
</script>

其他回答

我们可以使用PHP heredoc来实现:

<?php
    
$inPhpVar = "i am php var";

$ScriptInline = <<<JS
<script>
alert('{$inPhpVar} that used in js code');
</script>
JS;

echo $ScriptInline;

?>

我想尝试一个更简单的答案:

问题的解释

首先,让我们了解当一个页面从我们的服务器被服务时的事件流:

首先运行PHP,它生成提供给客户端的HTML。 然后,当HTML被交付给客户端时,PHP“死亡”(即它字面上停止运行)。我要强调的是,一旦代码离开服务器,PHP就不再是页面加载的一部分,服务器也不再有对它的访问权。 然后,当带有JavaScript的HTML到达客户端时,客户端可以在该HTML上执行JavaScript,前提是它是有效的JavaScript。

这里要记住的核心是HTTP是无状态的。一旦请求离开服务器,服务器就不能接触它。所以,我们的选择是:

在初始请求完成后,从客户端发送更多请求。 编码服务器在初始请求中必须说的内容。

解决方案

这是你应该问自己的核心问题:

我是在写网站还是应用程序?

网站主要是基于页面的,页面加载时间需要尽可能快(例如-维基百科)。Web应用程序使用AJAX较多,需要执行大量往返以快速获取客户端信息(例如—股票仪表板)。

网站

在初始请求完成后从客户端发送更多的请求会很慢,因为它需要更多的HTTP请求,这有很大的开销。此外,它需要异步性,因为发出一个AJAX请求需要一个处理程序来处理它何时完成。

除非您的站点是用于从服务器获取信息的应用程序,否则我不建议您再次发出请求。

你需要快速的响应时间,这对转换和加载时间有很大的影响。在这种情况下,Ajax请求的初始正常运行时间较慢,而且是不必要的。

你有两种方法来解决这个问题

设置cookie - cookie是在HTTP请求中发送的报头,服务器和客户端都可以读取。 将变量编码为JSON——JSON看起来非常接近JavaScript对象,大多数JSON对象都是有效的JavaScript变量。

设置cookie并不难,你只需要给它赋一个值:

setcookie("MyCookie", $value); // Sets the cookie to the value, remember, do not
                               // Set it with HTTP only to true.

然后,你可以使用document.cookie用JavaScript读取它:

这是一个简短的手动解析器,但我链接到上面的答案有更好的测试:

var cookies = document.cookie.split(";").
    map(function(el){ return el.split("="); }).
    reduce(function(prev,cur){ prev[cur[0]] = cur[1]; return prev },{});
alert(cookies["MyCookie"]); // Value set with PHP.

cookie用于保存少量数据。这就是跟踪服务经常做的事情。

一旦我们有了更多的数据,我们可以用JSON在JavaScript变量中进行编码:

<script>
    var myServerData = <?=json_encode($value)?>; // Don't forget to sanitize
                                                 //server data
</script>

假设$value在PHP端是json_encodeable的(通常是)。这项技术就是Stack Overflow在它的聊天中所做的(只是使用。net而不是PHP)。

应用程序

如果你正在编写一个应用程序——突然之间,初始加载时间就不总是像应用程序的持续性能那么重要了,并且开始将数据和代码分开加载。

我在这里的回答解释了如何在JavaScript中使用AJAX加载数据:

function callback(data){
    // What do I do with the response?
}

var httpRequest = new XMLHttpRequest;
httpRequest.onreadystatechange = function(){
    if (httpRequest.readyState === 4) { // Request is done
        if (httpRequest.status === 200) { // successfully
            callback(httpRequest.responseText); // We're calling our method
        }
    }
};
httpRequest.open('GET', "/echo/json");
httpRequest.send();

或者使用jQuery:

$.get("/your/url").done(function(data){
    // What do I do with the data?
});

现在,服务器只需要包含一个/your/url路由/文件,其中包含抓取数据并对其进行处理的代码,在你的例子中:

<?php
$val = myService->getValue(); // Makes an API and database call
header("Content-Type: application/json"); // Advise client of response type
echo json_encode($val); // Write it to the output

这样,我们的JavaScript文件请求数据并显示它,而不是要求代码或布局。这样更干净,并且随着应用程序的提高,效果开始显现。它还可以更好地分离关注点,并且允许在不涉及任何服务器端技术的情况下测试客户端代码,这是另一个优点。

附言:当您将任何东西从PHP注入到JavaScript时,您必须非常注意XSS攻击向量。正确地转义值是非常困难的,而且它是上下文敏感的。如果您不确定如何处理XSS,或者不知道它——请阅读这篇OWASP文章,这篇文章和这个问题。

实际上有几种方法可以做到这一点。有些比其他的需要更多的开销,有些被认为比其他的更好。

排名不分先后:

使用AJAX从服务器获取所需的数据。 将数据回显到页面的某处,并使用JavaScript从DOM获取信息。 将数据直接回显到JavaScript。

在这篇文章中,我们将研究上述每种方法,并了解每种方法的优缺点,以及如何实现它们。

1. 使用AJAX从服务器获取所需的数据

这种方法被认为是最好的,因为您的服务器端和客户端脚本是完全独立的。

Pros

Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code. More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages. Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever. Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

Cons

Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies. State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

实现示例

使用AJAX,你需要两个页面,一个是PHP生成输出的页面,另一个是JavaScript获得输出的页面:

get-data.php

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 *
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); // In the end, you need to `echo` the result.
                      // All data should be `json_encode`-d.

                      // You can `json_encode` any value in PHP, arrays, strings,
                      // even objects.

Index.php(或任何实际页面的命名方式)

<!-- snip -->
<script>
    fetch("get-data.php")
        .then((response) => {
            if(!response.ok){ // Before parsing (i.e. decoding) the JSON data,
                              // check for any errors.
                // In case of an error, throw.
                throw new Error("Something went wrong!");
            }

            return response.json(); // Parse the JSON data.
        })
        .then((data) => {
             // This is where you handle what to do with the response.
             alert(data); // Will alert: 42
        })
        .catch((error) => {
             // This is where you handle errors.
        });
</script>
<!-- snip -->

上述两个文件的组合将在文件加载完成时提醒42。

更多的阅读材料

使用Fetch API 如何从异步调用返回响应?

2. 将数据回显到页面的某处,并使用JavaScript从DOM获取信息

这种方法不如AJAX好,但仍然有它的优点。PHP和JavaScript之间仍然是相对分离的在某种意义上,JavaScript中没有PHP。

Pros

快速——DOM操作通常很快,您可以相对快速地存储和访问大量数据。

Cons

Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements. Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source. Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself. Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

实现示例

因此,我们的想法是创建某种元素,它不会显示给用户,但对JavaScript是可见的。

index . php

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

3.将数据直接回显到JavaScript

这可能是最容易理解的。

Pros

非常容易实现——它需要非常少的实现和理解。 不会弄脏源代码——变量直接输出到JavaScript,所以DOM不受影响。

Cons

将PHP与数据逻辑紧密结合——因为PHP用于表示,所以不能将两者清晰地分开。

实现示例

实现相对简单:

<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->

好运!

诀窍是这样的:

下面是使用该变量的“PHP”: <?php $name = 'PHP变量'; 回声的< >脚本; 返回'var name = '。json_encode()美元。';; 回声的> < /脚本; ? > 现在你有了一个名为“name”的JavaScript变量,下面是使用该变量的JavaScript代码: <脚本> console.log(“我无处不在”+名字); > < /脚本

假设变量总是整数。在这种情况下,这样做更容易:

<?PHP
    $number = 4;

    echo '<script>';
    echo 'var number = ' . $number . ';';
    echo 'alert(number);';
    echo '</script>';
?>

输出:

<script>var number = 4;alert(number);</script>

假设你的变量不是整数,但如果你尝试上面的方法,你会得到这样的结果:

<script>var number = abcd;alert(number);</script>

但在JavaScript中,这是一个语法错误。

在PHP中,我们有一个函数json_encode,它将字符串编码为JSON对象。

<?PHP
    $number = 'abcd';

    echo '<script>';
    echo 'var number = ' . json_encode($number) . ';';
    echo 'alert(number);';
    echo '</script>';
?>

因为abcd在JSON中是“abcd”,它看起来像这样:

<script>var number = "abcd";alert(number);</script>

你可以对数组使用相同的方法:

<?PHP
    $details = [
    'name' => 'supun',
    'age' => 456,
    'weight' => '55'
    ];

    echo '<script>';
    echo 'var details = ' . json_encode($details) . ';';
    echo 'alert(details);';
    echo 'console.log(details);';
    echo '</script>';
?>

你的JavaScript代码看起来是这样的:

<script>var details = {"name":"supun","age":456,"weight":"55"};alert(details);console.log(details);</script>

控制台输出