我在PHP中有一个变量,我的JavaScript代码中需要它的值。如何将变量从PHP转换为JavaScript?
我有看起来像这样的代码:
<?php ... $val = $myService->getValue(); // Makes an API and database call ?>
我有需要val和看起来类似以下内容的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>
实际上,有几种方法可以做到这一点。有些需要比其他更多的开销,有些被认为比其他更好。
没有特别的顺序:
在本文中,我们将研究上述每种方法,并了解每种方法的优缺点以及如何实现它们。
这种方法被认为是最佳方法,因为 服务器端脚本和客户端脚本是完全分开的 。
使用AJAX,您需要两个页面,一个页面是PHP生成输出的位置,第二个页面是JavaScript获取该输出的位置:
/* 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.
<!-- snip --> <script> function reqListener () { console.log(this.responseText); } var oReq = new XMLHttpRequest(); // New request object oReq.onload = function() { // This is where you handle what to do with the response. // The actual data is found on this.responseText alert(this.responseText); // Will alert: 42 }; oReq.open("get", "get-data.php", true); // ^ Don't block the rest of the execution. // Don't wait until the request finishes to // continue. oReq.send(); </script> <!-- snip -->
42当文件完成加载时,两个文件的上述组合将发出警报。
42
这种方法不如AJAX更好,但仍具有其优点。它仍然 比较 PHP和JavaScript之间的感觉,有没有直接PHP在JavaScript中分离出来。
<input type=hidden>
inputNode.value
<meta>
data-*
这样做的想法是创建某种元素,该元素不会显示给用户,但对JavaScript可见。
<!-- 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 -->
这可能是最容易理解的。
实施相对简单:
<!-- snip --> <script> var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon! </script> <!-- snip -->