Won*_*ing -1 javascript jquery
通过JavaScript我将一个查询参数附加到页面网址,我面临一个奇怪的行为.
<div>
<a href="Default3.aspx?id=2">Click me</a>
</div>
$(function () {
window.location.href = window.location.href + "&q=" + "aa";
});
Run Code Online (Sandbox Code Playgroud)
现在我附加&q=aa在default3.aspx中,并且在此页面中&q=aa连续添加,导致URL变为:
http://localhost:1112/WebSite2/Default3.aspx?id=2&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa&q=aa
Run Code Online (Sandbox Code Playgroud)
有人会说它只是传递它<a href="Default3.aspx?id=2&q=aa">Click me</a>,但我不能这样做.此查询参数的值实际上是default3.aspx中的HTML元素的值.我必须在运行时添加它.
有什么方法可以达到这个目的?
发生这种情况的原因是,如果您更改了window.location值,浏览器将执行重定向到新位置,并且当您这样做时,这将document.ready无限期地发生.
在执行此重定向之前,您可能需要检查当前URL是否已包含这些参数.
$(function () {
var suffix = '&q=aa';
var currentUrl = window.location.href;
if (currentUrl.match(suffix + '$') != suffix) {
window.location.href = window.location.href + suffix;
}
});
Run Code Online (Sandbox Code Playgroud)
备注:对我来说,使用javascript似乎是一个坏主意.我会在服务器端执行此重定向,这将更可靠.在default.aspx页面中:
protected void Page_Load(object sender, EventArgs e)
{
var q = Request["q"];
if (string.IsNullOrEmpty(q))
{
// q parameter has not been set => redirect
Response.Redirect("/default.aspx?q=aa");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2324 次 |
| 最近记录: |