window.location.href中的正斜杠重定向到根URL

时间:2017-01-25 19:54:22

标签: javascript

我正在生成window.location.href属性,其中路径有时可以包含斜杠" /"。

ImageButton.Attributes.Add("OnClick", "window.location.href='DynamicItemDetail.aspx?Partno=" & strItemCode & "&Decorloc='")

最终字符串如下所示:

window.location.href="myurl.com/products.aspx?_Category=130&Partno=WWS-AWT/SWD&Decorloc="

不幸的是,由于商品代码包含斜杠,因此window.location重定向到根网址。反正有没有告诉Javascript不要将斜杠视为子目录?

4 个答案:

答案 0 :(得分:2)

您需要转义URL中的字符。 encodeURIComponent正是您所寻找的。

var encodedItemCode = encodeURIComponent(strItemCode);
ImageButton.Attributes.Add("OnClick", "window.location.href='DynamicItemDetail.aspx?Partno=" + encodedItemCode + "&Decorloc='")

结果网址为

myurl.com/products.aspx?_Category=130&Partno=WWS-AWT%2FSWD&Decorloc=

答案 1 :(得分:1)

使用encodeURIComponent() Javascript函数将斜杠和任何其他特殊字符编码为允许在URI中使用的格式。

该功能的一个很好的参考是:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

答案 2 :(得分:0)

您需要将斜杠转义为%2F

答案 3 :(得分:0)

是。您应该对字符串或斜杠进行URL编码。所以,而不是" /"你使用"%2F"