如何在PHP生成的HTML中将URL编码为JavaScript字符串? [英] How to encode a URL as javascript string in PHP-generated HTML?

查看:90
本文介绍了如何在PHP生成的HTML中将URL编码为JavaScript字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出这个PHP代码:

Given this PHP code:

<a onclick="javascript:window.location.href='<?php echo $url;?>'"

如果有 '在$ url?

我尝试使用 json_encode($ url),但它将无法处理此问题。

I tried using json_encode($url) but it won't be able to handle this.

推荐答案

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.

这篇关于如何在PHP生成的HTML中将URL编码为JavaScript字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆