且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在PHP生成的HTML中将URL编码为JavaScript字符串?

更新时间:2023-02-23 10:53:42

json_encode 。您只需以正确的方式使用它:

json_encode will work. You just have to use it the right way:

<a onclick="javascript:window.location.href=<?php echo htmlspecialchars(json_encode($url)); ?>">

这将会起作用,因为 json_encode 已经返回带引号的JavaScript表达式。需要 htmlspecialchars 来转义可能的HTML元字符。

This will work since json_encode already returns an JavaScript expression with quotes. And htmlspecialchars is needed to escape possible HTML meta characters.