JavaScript 的 magento 转义字符串第 2 部分
,我接受了@AlanStorm建议,使用json_encode来转义字符串文字。
但我现在这个解决方案遇到了一个新问题。
当尝试转义其中包含 / 的 URL 以将其呈现为 JavaScript 的字符串文字时,json_encode 似乎在 / 前面添加了多余的 \ 。
这里有什么新建议吗?
解决方案应该采用一个字符串变量并返回一个可以正确计算为 JavaScript 中的字符串文字的字符串。 (我不在乎它是用单引号还是双引号引起来的 - 尽管我更喜欢单引号。而且它还必须支持字符串中的换行符。)
谢谢
This is a follow up on
magento escape string for javascript
where I accepted @AlanStorm suggestion to use json_encode to escape string literals.
But I now have a new problem with this solution.
when trying to escape a URL that has /'s in it to be rendered as a string literal for JavaScript json_encode seems to add redundant \'s in front of the /'s.
Any new suggestions here?
solutions should take a string variable and return a string that would properly be evaluated to a string literal in JavaScript. (I don't care if its surrounded with single or double quotes - although I prefer single quotes. And it must also support newlines in the string.)
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
详细信息可以在这里找到 http://bugs.php.net/bug.php?id= 49366
解决此问题:
对于您的问题,您可以执行类似的操作
希望这会有所帮助
Details can be found here http://bugs.php.net/bug.php?id=49366
work around for this issue:
for your issue you can do something like
Hope this helps
当我检查 JSON 格式 时,我发现 Solidi 被允许转义,因此
json_encode
实际上工作正常。(来源:json.org)
satrun77 发布的错误链接甚至说“转义斜杠并没有错。”
如果你坚决不做并且(在这种情况下)肯定要使用字符串,你可以使用这样的黑客:
显然这对更复杂的结构没有帮助,但幸运的是,你正在使用 Magento这是高度可修改的。将 lib/Zend/Json/Encoder.php 复制到 app/core/local/Zend/Json/Encoder.php (形成覆盖)并修复它的
_encodeString
方法。When I check the JSON format I see that solidi are allowed to be escaped so
json_encode
is in fact working correctly.(source: json.org)
The bug link posted by satrun77 even says "It's not incorrect to escape slashes."
If you're adamant to do without and (in this case) are certain to be working with a string you can use a hack like this:
Obviously that doesn't help for more complicated structures but as luck has it, you are using Magento which is highly modifiable. Copy
lib/Zend/Json/Encoder.php
toapp/core/local/Zend/Json/Encoder.php
(which forms an override) and fix it's_encodeString
method.