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



我正在生成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 重定向到根 URL。有没有办法告诉Javascript不要将斜杠视为子目录?

您需要对 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=

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

该函数的一个很好的参考在这里:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

您需要

将斜杠转义为%2F

是的。 您应该对字符串或斜杠进行 URL 编码。 因此,您可以使用"%2F"代替"/"

最新更新