即使使用unescape,decodeURIComponent也无法正常工作

时间:2013-12-10 07:26:06

标签: javascript

我有一个图像URL,其中decodeURIComponent正在使用它。我也尝试了unescape,但仍然没有运气。我不能在这里使用JQuery。我需要一个使用普通JS解决这个问题的解决方案。

我还没有给出实际的代码,但这里有一个代码片段,其中包含要编码和解码的URL。

编码URL功能正常但解码功能失败。

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to encode and decode a URI.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var uri = "http://lp.imageg.net/prod?set=key[initials],value[ABC]&set=key[color],value[blind stamp]&set=key[displaysize],value[64%]&load=url[http://chains.imageg.net/graphics/dynamic/chains/TUMI_TAG1.chain]";
var uri_enc = "Encoded URI: " + encodeURIComponent(uri);
alert(uri_enc);
var uri_dec = "Decoded URI: " + decodeURIComponent(unescape(uri));
var uri_dec = "Decoded URI: " + decodeURIComponent(uri);
alert(uri_dec);
var res = uri_enc + "<br>" + uri_dec;
document.getElementById("demo").innerHTML=res;

}
</script>

</body>
</html> 

1 个答案:

答案 0 :(得分:1)

你做错了......这里有更新的代码......

Demo Fiddle

    <!DOCTYPE html>
    <html>
    <body>
    <p id="demo">Click the button to encode and decode a URI.</p>
    <button onclick="myFunction()">Try it</button>
    <script>
        function myFunction() {
            var uri = "http://lp.imageg.net/prod?set=key[initials],value[ABC]&set=key[color],value[blind stamp]&set=key[displaysize],value[64%]&load=url[http://chains.imageg.net/graphics/dynamic/chains/TUMI_TAG1.chain]";
            var uri_enc = "Encoded URI: " + encodeURIComponent(uri).replace(/'/g, "%27").replace(/"/g, "%22");
            alert(uri_enc);
            var uri_dec = "Decoded URI: " + decodeURIComponent(uri_enc.replace(/\+/g, " "));
            alert(uri_dec);
            var res = uri_enc + "<br>" + uri_dec;
            document.getElementById("demo").innerHTML = res;

        }
    </script>
</body>
    </html>