是这样的:
$html .= "<table>"
$html .= "<tr onclick=\"test(" . $phpvar . ")\"><td>test</td></tr>";
$html .= "</table>"
$rVal=array("htmltable" => $html);
echo json_encode($rVal);
JS:
success: function(data){
$("#content").html(data.htmltable);
可能吗?
当不涉及 PHP var 时一切正常,但我问是否有办法像这样传递 PHP var ...
最佳答案
It's correct (functioning without error) ... the value of $phpvar is a string of a person's first and last name, and nickname
因此:
$phpvar = "John 'the Something' Smith";
$html
的值为:
<table><tr onclick="test(John 'the Something' Smith)"><td>test</td></tr></table>
因此 John
将被视为 JavaScript 变量名称。然后你会遇到语法错误。
您需要将数据编码为 JavaScript 字符串文字。 json_encode
会做到这一点。
$phpvar = "John 'the Something' Smith";
$javascript_literal = json_encode($phpvar);
$html = "";
$html .= "<table>";
$html .= "<tr onclick=\"test(" . $javascript_literal . ")\"><td>test</td></tr>";
$html .= "</table>";
print $html;
...但这仍然行不通,因为它会给你:
<table><tr onclick="test("John 'the Something' Smith")"><td>test</td></tr></table>
…并且"
将终止属性值。
因此您还需要将其编码为 HTML。
$phpvar = "John 'the Something' Smith";
$javascript_literal = json_encode($phpvar);
$html_attribute_value = htmlspecialchars($javascript_literal);
$html = "";
$html .= "<table>";
$html .= "<tr onclick=\"test(" . $html_attribute_value . ")\"><td>test</td></tr>";
$html .= "</table>";
print $html;
这会给你:
<table><tr onclick="test("John 'the Something' Smith")"><td>test</td></tr></table>
...这会起作用。
<小时/>但这太可怕了。并引起头痛。所以不要这样做。
- 将数据而不是标记传递回客户端。
- 为任务使用适当的标记。你想要点击一些东西吗?使用按钮。不是 table 。
例如:
$rVal = array("plaindata" => $phpvar);
header("Content-Type: application/json");
echo json_encode($rVal);
和
success: function(data) {
$("#content")
.empty()
.append(
$("<button />")
.text("test")
.on("click", function() { test(data.plaindata); })
);
}
关于javascript - 在通过 AJAX 传递给 JavaScript 函数的 HTML 字符串中插入 PHP 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36340680/