Javascript 从请求 url 获取哈希参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8033537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:28:33  来源:igfitidea点击:

Getting hash parameters from request url

javascript

提问by nKognito

I have such url - http://www.coolsite.com/daily-plan/#id=1What the easiest way to parse that string and read a hash value (the value after #id=)? Thank you

我有这样的网址 - http://www.coolsite.com/daily-plan/#id=1解析该字符串并读取哈希值(#id= 之后的值)的最简单方法是什么?谢谢

回答by Kirill Muzykov

On client side (i.e. from JavaScript) you can check window.location.hashto get hash. On server side, general answer is 'it is impossible' since hash is not sent in request to server.

在客户端(即来自 JavaScript),您可以检查window.location.hash以获取哈希。在服务器端,一般的答案是“不可能”,因为哈希不会在请求中发送到服务器。

Upd:I maybe misunderstood the question. My answer is about how to get hash part of url either in browser or in server side code during request processing, not about string processing.

更新:我可能误解了这个问题。我的答案是关于如何在请求处理期间在浏览器或服务器端代码中获取 url 的哈希部分,而不是关于字符串处理。

Upd2:Answer to comment here because it doesn't fit in comment.

Upd2:在这里回答评论,因为它不适合评论。

How does it work when user clicks on your navigational links?

当用户点击你的导航链接时它是如何工作的?

I assume hash is changed and corresponding content is downloaded via AJAX request from web service or REST.

我假设哈希已更改,并通过来自 Web 服务或 REST 的 AJAX 请求下载相应的内容。

For example if your user has URL www.example.com in his browser and this page shows a list of product categories. User clicks one category and URL changes to www.example.com/#id=5 and products from that category(with ID=5) are downloaded via AJAX and shown on the page. No postback, only partial page refresh.

例如,如果您的用户在其浏览器中有 URL www.example.com 并且此页面显示产品类别列表。用户单击一个类别,URL 更改为 www.example.com/#id=5,来自该类别的产品(ID=5)通过 AJAX 下载并显示在页面上。没有回发,只有部分页面刷新。

Is this close to your scenario?

这接近你的场景吗?

Now you want user to paste/enter www.example.com/#id=5 directly in the browser address bar and go directly to list of products in that category.

现在您希望用户直接在浏览器地址栏中粘贴/输入 www.example.com/#id=5 并直接转到该类别中的产品列表。

But /#id=5 is not sent to server with requestby the browser, so there is no way to get that value on server side, and you can do nothing about it since it is the browser decided not to send this data and you don't have it on server side.

但是/#id=5 不会通过浏览器的请求发送到服务器,因此无法在服务器端获取该值,并且您无能为力,因为浏览器决定不发送此数据而您在服务器端没有它。

In our project we use solution when server returns only common page code/html, i.e. header, footer, without main/center part of the page. Then there is a JavaScript code which executes right after this common HTML loaded. It takes window.location.hashand sends it to web service via AJAX and web service returns content (HTML) for the main part of the page.

在我们的项目中,当服务器仅返回公共页面代码/html,即页眉、页脚,而没有页面的主要/中心部分时,我们使用解决方案。然后有一段 JavaScript 代码,它会在这个常见的 HTML 加载后立即执行。它window.location.hash通过 AJAX获取并将其发送到 Web 服务,Web 服务返回页面主要部分的内容 (HTML)。

回答by ptomli

new URI("http://.../abc#xyz").getFragment();

See the Javadocs for URI

请参阅URIJavadocs

回答by Richard Boardman

Here is how to capture anchor links. Works across all web frameworks.

这是捕获锚链接的方法。适用于所有 Web 框架。

I'll use an example scenario to illustrate: let's say we need to capture a deep URL http://server.com/#/xyzrequested by an unauthenticated user so that they can be redirected to that deep URL post-login.

我将使用一个示例场景来说明:假设我们需要捕获未经身份验证的用户请求的深层 URL http://server.com /#/xyz,以便他们可以在登录后重定向到该深层 URL。

  1. The unauthenticated user requests http://server.com/#/xyz(everything from the '#' onwards is not sent to the server).

  2. All the server knows is that the user wants http://server.com/and that they are unauthenticated. Server redirects the user to a login form.

  3. Here's the clever bit: the client is still waiting on their original request so if the server includes a hidden element in the login form with some JS that references window.location.href, it can capture the full URL of the original requestcomplete with the anchor portion:

    <form action="/login" method="post">
      <div>
        <label>Username:</label>
        <input type="text" name="username"/><br/>
      </div>
      <div>
        <label>Password:</label>
        <input type="password" name="password"/>
      </div>
      <!-- XXXXXXXXX CLEVER BIT XXXXXXXXXX-->
      <script>
        document.write('<input type="hidden" name="from" value="'+document.location.href+'"/>');
      </script>
      <!-- XXXXXXXXXX-->
      <div>
        <input class="submit-button" type="submit" value="Submit"/>
      </div>
    </form>
    
  4. The user authenticates themself and the original URL is sent with the POST. The server can then relay the user to the original deep URL.

  1. 未经身份验证的用户请求http://server.com /#/xyz(从“#”开始的所有内容都不会发送到服务器)。

  2. 服务器只知道用户想要http://server.com/并且他们未经身份验证。服务器将用户重定向到登录表单。

  3. 这是一个聪明的地方:客户端仍在等待他们的原始请求,所以如果服务器在登录表单中包含一个隐藏元素,其中包含一些引用 window.location.href 的 JS,它可以捕获原始请求的完整 URL 并带有锚定部分:

    <form action="/login" method="post">
      <div>
        <label>Username:</label>
        <input type="text" name="username"/><br/>
      </div>
      <div>
        <label>Password:</label>
        <input type="password" name="password"/>
      </div>
      <!-- XXXXXXXXX CLEVER BIT XXXXXXXXXX-->
      <script>
        document.write('<input type="hidden" name="from" value="'+document.location.href+'"/>');
      </script>
      <!-- XXXXXXXXXX-->
      <div>
        <input class="submit-button" type="submit" value="Submit"/>
      </div>
    </form>
    
  4. 用户对自己进行身份验证,原始 URL 与 POST 一起发送。然后服务器可以将用户中继到原始深层 URL。

回答by Mayur Rokade

REPLACE the '#' with '?'when parsing the url. Check the code below

用 '?' 替换 '#' 解析网址时。检查下面的代码

String url = "http://www.coolsite.com/daily-plan/#id=1";
String urlNew = url.replace("#", "?");
String id = Uri.parse(urlNew).getQueryParameter("id");

回答by AlexR

String url = " http://www.coolsite.com/daily-plan/#id=1";
int sharpPos = url.indexOf('#');
String q = null;
if (sharpPos >= 0) {
    q = url.substring(sharpPos);
}

Surely you can use various methods of string manipulation including regular expressions.

当然,您可以使用各种字符串操作方法,包括正则表达式。

But actually your example is strange. Typically parameters of URL are passed after question mark. In this case you can just use standard class URL:

但实际上你的例子很奇怪。URL 的参数通常在问号后传递。在这种情况下,您可以只使用标准类 URL:

String q = new URL(" http://www.coolsite.com/daily-plan?id=1").getQuery();

String q = new URL(" http://www.coolsite.com/daily-plan?id=1").getQuery();

回答by Hemant Metalia

what you are using to do this ?

你用什么来做到这一点?

If you are using jsp or servlet following will be useful to you

如果您使用的是 jsp 或 servlet,以下将对您有用

if (request.getParameter("#id") == null) {
    out.println("Please enter your name.");
} else {
    out.println("Hello <b>"+request.getParameter(i)+"</b>!");
}

If you are using javascript for it following function will be useful to you

如果您正在使用 javascript,以下功能将对您有用

function getURLParameters() 
{
var sURL = window.document.URL.toString();

if (sURL.indexOf("?") > 0)
{
    var arrParams = sURL.split("?");

    var arrURLParams = arrParams[1].split("&");

    var arrParamNames = new Array(arrURLParams.length);
    var arrParamValues = new Array(arrURLParams.length);

    var i = 0;
    for (i=0;i<arrURLParams.length;i++)
    {
        var sParam =  arrURLParams[i].split("=");
        arrParamNames[i] = sParam[0];
        if (sParam[1] != "")
            arrParamValues[i] = unescape(sParam[1]);
        else
            arrParamValues[i] = "No Value";
    }

    for (i=0;i<arrURLParams.length;i++)
    {
        alert(arrParamNames[i]+" = "+ arrParamValues[i]);
    }
}
else
{
    alert("No parameters.");
}
   }

回答by Psycho

If you URL will the same as you write and doesn't contains anythins else then whis code on Java will help you

如果您的 URL 与您编写的相同并且不包含任何其他内容,那么 Java 上的代码将帮助您

 String val = "http://www.coolsite.com/daily-plan/#id=1";
 System.out.println(val.split("#id")[1]);

Don't forget check to null value.

不要忘记检查空值。

P.S. If you use servlet you can get this parameter from request.getAttribute("id").

PS 如果您使用 servlet,您可以从 request.getAttribute("id") 获取此参数。

With best regards, Psycho

最好的问候,心理