如何从服务器端获取 Url Hash (#) [英] How to get Url Hash (#) from server side

查看:63
本文介绍了如何从服务器端获取 Url Hash (#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在客户端(javascript)你可以使用 windows.location.hash 但无论如何都找不到从服务器端访问.我正在使用 asp.net.

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.

推荐答案

我们遇到了一种情况,需要在 ASP.Net 回发中保留 URL 哈希.由于浏览器默认情况下不会将哈希发送到服务器,因此唯一的方法是使用一些 Javascript:

We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:

  1. 当表单提交时,获取哈希值 (window.location.hash) 并将其存储在服务器端隐藏输入字段中 将其放入一个 id 为urlhash" 以便我们以后可以轻松找到它.

  1. When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.

在服务器上,如果您需要对其进行处理,可以使用该值.如果需要,您甚至可以更改它.

On the server you can use this value if you need to do something with it. You can even change it if you need to.

在页面加载客户端时,检查此隐藏字段的值.您将希望通过它包含的 DIV 找到它,因为自动生成的 ID 是未知的.是的,您可以在这里使用 .ClientID 做一些小伎俩,但我们发现仅使用包装 DIV 更简单,因为它允许所有这些 Javascript 存在于外部文件中并以通用方式使用.

On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.

如果隐藏输入字段具有有效值,则将其设置为 URL 哈希(window.location.hash 再次)和/或执行其他操作.

If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.

我们使用 jQuery 来简化字段的选择等......总而言之,它最终成为了几次 jQuery 调用,一个是保存值,另一个是恢复它.

We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.

提交前:

$("form").submit(function() {
  $("input", "#urlhash").val(window.location.hash);
});

页面加载时:

var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
  window.location.hash = hashVal;
}

IsHashValid() 可以检查undefined"或其他您不想处理的事情.

IsHashValid() can check for "undefined" or other things you don't want to handle.

另外,当然要确保适当地使用 $(document).ready().

Also, make sure you use $(document).ready() appropriately, of course.

这篇关于如何从服务器端获取 Url Hash (#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆