P粉8934570262023-08-22 09:30:13
I usually use data-* attributes in HTML.
<div class="service-container" data-service="<?= htmlspecialchars($myService->getValue()) ?>" > </div> <script> $(document).ready(function() { $('.service-container').each(function() { var container = $(this); var service = container.data('service'); // Var "service" now contains the value of $myService->getValue(); }); }); </script>
This example uses jQuery, but it can be adapted to other libraries or native JavaScript.
You can read more about the dataset attribute here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset
P粉5170907482023-08-22 09:17:08
There are actually several ways to do this. Some methods require more overhead, and some are considered better than others.
In no particular order:
In this article, we will detail the pros and cons of each of the above methods, and how to implement them.
This approach is considered the best because server-side and client-side scripts are completely separated .
To use AJAX, you need two pages, one where PHP generates the output, and another where JavaScript gets the output:
/* 在这里执行一些操作,比如与数据库、文件会话等进行交互 * 超越世界,无间地带,闪烁之城和加拿大。 * * AJAX通常使用字符串,但你也可以输出JSON、HTML和XML。 * 这完全取决于你发送的AJAX请求的Content-type头。 */ echo json_encode(42); // 最后,你需要`echo`结果。 // 所有数据都应该使用`json_encode`。 // 你可以在PHP中`json_encode`任何值,数组、字符串, // 甚至对象。
<!-- 省略 --> <script> fetch("get-data.php") .then((response) => { if(!response.ok){ // 在解析(即解码)JSON数据之前, // 检查是否有任何错误。 // 如果有错误,抛出错误。 throw new Error("Something went wrong!"); } return response.json(); // 解析JSON数据。 }) .then((data) => { // 在这里处理响应。 alert(data); // 将弹出:42 }) .catch((error) => { // 在这里处理错误。 }); </script> <!-- 省略 -->
The combination of the above two files will pop up 42
when the file loading is completed.
This method is less desirable than AJAX, but it still has its advantages. In a way, it's still relatively separated between PHP and JavaScript, since PHP is not used directly in JavaScript.
<input type=hidden>
to store the information because from inputNode.value
It's easier to get the information in, but doing so means you have a meaningless element in your HTML. HTML has the <meta>
element for document data, and HTML 5 introduces the data-*
attribute for JavaScript-related data on specific elements. In this case, you need to create some kind of element that is invisible to the user but visible to JavaScript.
<!-- 省略 --> <div id="dom-target" style="display: none;"> <?php $output = "42"; // 再次,执行一些操作,获取输出。 echo htmlspecialchars($output); /* 必须转义,否则结果 将不是有效的HTML。 */ ?> </div> <script> var div = document.getElementById("dom-target"); var myData = div.textContent; </script> <!-- 省略 -->
This is probably the easiest way to understand.