开发者

magento escape string for JavaScript part 2

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 开发者_如何学Cshould 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


some more info: how comes '/');echo json_encode($v); ?> results in {"a":"\/"} ?

Details can be found here http://bugs.php.net/bug.php?id=49366

work around for this issue:

str_replace('\\/', '/', $jsonEncoded);

for your issue you can do something like

$jsonDecoded = str_replace(array("\\/", "/'s"), array("/", "/\'s"), $jsonEncoded);

Hope this helps


When I check the JSON format I see that solidi are allowed to be escaped so json_encode is in fact working correctly.

magento escape string for JavaScript part 2


(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:

echo '["', addslashes($string), '"]';

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 to app/core/local/Zend/Json/Encoder.php (which forms an override) and fix it's _encodeString method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜