how to get the parameter from a url?

2019-02-25 01:01发布

i have a url like this. http://localhost:8080/steer/trip/create/3. where in my page i want to get value "3" using the jquery . please help me

6条回答
欢心
2楼-- · 2019-02-25 01:22

Plain js

var arr = (window.location.pathname).split("/");
var val = (arr[arr.length-1]);

The value that you require is in val

查看更多
戒情不戒烟
3楼-- · 2019-02-25 01:24

It may be overkill here, but for URL parsing, I found this useful:

A jQuery plugin to parse urls and provides easy access to information within them, such as the protocol, host, port, the segments that make up the path and the various query string values.

In your case, this would boil down to something like:

jQuery.url.setUrl("http://localhost:8080/steer/trip/create/3").segment("4");
查看更多
女痞
4楼-- · 2019-02-25 01:25

This will output "3" or basically the whole last segment of the url after the last "/" slash.

var urlsegment = top.location.href.match(/([^\/]+)$/)[1]
查看更多
我命由我不由天
5楼-- · 2019-02-25 01:27

Here is a easy to read and understand JS function that you can use to retrieve any variable from url.

All you need to do is call this function with name of the variable that you want to filter and it will return the value back to you.

Hope it helps:

function getVarFromURL(varName){
            var url = window.location.href;
            url = url.substring(url.indexOf('?'));
            var urlLowerCase = url.toLowerCase();
            varName = varName.toLowerCase();
            if (urlLowerCase.indexOf(varName + "=") != -1) {
                var value = url.substring(urlLowerCase.indexOf(varName) + varName.length + 1);
                if (value.indexOf('&') != -1) {
                    value = value.substring(0, value.indexOf('&'));
                }
                return value;
            }
            else {
                return null;
            }
}
查看更多
疯言疯语
6楼-- · 2019-02-25 01:32

From: Highlight a button based on location

var pathname = window.location.pathname.split("/");
var filename = pathname[pathname.length-1];

alert(filename);
查看更多
走好不送
7楼-- · 2019-02-25 01:35

I am assuming you want to access the parameter value of your controller's action method via jQuery in the client.

In such case, I would rather emit the parameter value as a metadata in a view and query it with jQuery instead of parsing the url itself (you need to decide where to emit, though).

In ASP.NET MVC, if you have a Route that accepts the following pattern: {controller}{action}{param}, http:\myhost\mycontroller\myaction\3 and http:\myhost\mycontroller\myaction?param=3 are equivalent and parsing only one URL pattern will not be sufficient.

You may find examples in jQuery mdatadata plugin useful.

The following is one of the examples in the link above.

<li class="someclass {some: 'data'} anotherclass">...</li>
<script>alert($('li.someclass').metadata().some);</script>

Please disregard this answer if my assumption is not correct.

查看更多
登录 后发表回答