【发布时间】:2021-08-08 06:48:59
【问题描述】:
我正在尝试将 PHP 中的字符串作为 JavaScript 函数中的字符串变量回显。它没有按需要输出。我该如何解决这个问题?
<?php
$example1 = "example 1";
$example2 = "example 2";
$example3 = "example 3';
$string = $example1.", ".$example2.", ".$example3;
echo "<script>function testFunction(string) {console.log(string);}</script>";
echo "<button onclick='testFunction(".$string.")'>Test</button>";
?>
所需输出:<button onclick='testFunction("example 1, example 2, example 3")'>Test</button>
实际输出:<button onclick='testFunction("example 1" example 2= example 3=)'>Test</button>
【问题讨论】:
-
更好的方法:完全避免内联处理程序,它们太可怕了
-
我应该如何将唯一数据从 PHP 传递到 HTML 中的特定按钮以使用该数据执行 JavaScript?
-
我更喜欢
<script标签中的 JSON,或者数据属性,或者单独的网络请求。如何构建它取决于解决方案的通用性 - 例如,如果您有多个按钮 -
我确实有多个按钮,每个按钮都有自己独特的字符串参数。那么在按钮上放置一个数据属性,该属性对应于脚本标签中 JSON 数据中的字符串?还是将数据设为数据属性?
标签: javascript php html string echo