使用 jQuery 获取当前的 URL?

I am using jQuery. How do I get the path of the current URL and assign it to a variable?

Example URL:

http://localhost/menuname.de?foo=bar&number=0

转载于:https://stackoverflow.com/questions/406192/get-current-url-with-jquery

csdnceshi67
bug^君 No, there is no jQuery way to get the location; as of the jQuery bug tracker: »It may have worked but it was never supported or documented. Simply use document.location.href which is faster, simpler, and easier to understand.« In other words, some folks used jQuery to get the location, but they relied on a bug, rather than feature. See: bugs.jquery.com/ticket/7858
大约 5 年之前 回复
csdnceshi61
derek5. possible duplicate of Get current URL with JavaScript?
大约 6 年之前 回复
csdnceshi54
hurriedly% I think the question should be restored to asking for jQuery, since there is an answer for that, regardless of whether jQuery is required to accomplish the task.
6 年多之前 回复
weixin_41568196
撒拉嘿哟木头 you can see also tech-blog.maddyzone.com/javascript/…
接近 7 年之前 回复

30个回答

To get the path, you can use:

var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL
var origin   = window.location.origin;   // Returns base URL
csdnceshi76
斗士狗 Does not work on local network
2 年多之前 回复
csdnceshi58
Didn"t forge do you know how one would be able to get only the /menuname part, I have a url that is basesite/public/home and I need to get the Home part from that url
5 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 pointers are still cool
5 年多之前 回复
csdnceshi59
ℙℕℤℝ Here is a great listing of all properties with examples of the location object: tech-blog.maddyzone.com/javascript/…
5 年多之前 回复
csdnceshi80
胖鸭 Ummm,... window.location.pathname only gets the URL up the "?" and doesn't get the query params as asked in the question.
7 年多之前 回复
csdnceshi70
笑故挽风 LOL, why are "pointers" always used as a reference to "the olden days"... it's just a pointer. It's more appropriate in this context to hearken back to char[] and having to build a string.h to handle myVar = "A really complex object called STRING";
大约 8 年之前 回复
csdnceshi67
bug^君 True, you need window.location.hash to get the hash from the URL.
9 年多之前 回复
weixin_41568131
10.24 this doesn't work for the full url. for example. for "mail.google.com/mail/u/0/#mbox/13005b79fe72f448" this will only return /mail/u/0
9 年多之前 回复
csdnceshi57
perhaps? "How do I XYZ in jQuery" and the answer being plain javascript is pretty common. You may know how to do something in plain javascript; however, due to browser inconsistencies you may prefer to do it the "jQuery" way. I remember pre-jQuery or framework I would first check browser and then do what I wanted a handful of ways. So is jQuery killing plain js... yes, thank god, but it is also making it usable.
9 年多之前 回复
csdnceshi74
7*4 Far from killing it, jQuery's given Javascript a new life. Do new C#/Java programmers understand pointers? No. Do they need to? Not really, newer abstractions are powerful enough for it not to matter..
9 年多之前 回复
csdnceshi79
python小菜 Properties of the location object: developer.mozilla.org/en/DOM/window.location
10 年多之前 回复

In pure jQuery style:

$(location).attr('href');

The location object also has other properties, like host, hash, protocol, and pathname.

csdnceshi57
perhaps? You shouldn't be able to do .attr() on location. (1) It's not an element, so $(location) is shady at best, and (2) even if it worked, you should be using .prop() to get properties. .attr() is for HTML attributes.
7 年多之前 回复
csdnceshi73
喵-见缝插针 +1 Because I didn't even know you could do .attr() on location. But it's better to use window.location.
接近 8 年之前 回复
weixin_41568127
?yb? This answer is not needed, and question and answer can be updated to not use jquery. Reasons can be found here bugs.jquery.com/ticket/7858#comment:4
8 年多之前 回复
csdnceshi64
游.程 The "invalid" part applies to the request to support $(location); this should NOT be used.
8 年多之前 回复
csdnceshi61
derek5. Bug closed as invalid.
8 年多之前 回复
csdnceshi64
游.程 Apparently, using $(location) in jQuery is unsupported and advised against: bugs.jquery.com/ticket/7858
大约 9 年之前 回复
http://www.refulz.com:8082/index.php#tab2?foo=789

Property    Result
------------------------------------------
host        www.refulz.com:8082
hostname    www.refulz.com
port        8082
protocol    http:
pathname    index.php
href        http://www.refulz.com:8082/index.php#tab2
hash        #tab2
search      ?foo=789

var x = $(location).attr('<property>');

This will work only if you have jQuery. For example:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>
csdnceshi68
local-host According to bugs.jquery.com/ticket/7858 this is working only by accident. Also, attr is supposed to only be used on DOM objects, for things which can be set by using HTML attributes.
3 年多之前 回复
weixin_41568184
叼花硬汉 Personally, I believe this is the best answer. Of course Javascript tries its best, but jQuery better solves more edge cases, which is why jQuery is still so popular today, it better figures out the incompatibilities. Hypothetically, next year some new browser doesn't use window.location correctly, and in that case my money would be on jQuery. Yes, Javascript has improved since 1994, but now you have smartphones, tablets, so many browsers, more edge cases. It's funny to hear new developers call jQuery "the old way," but then their purist Javascript code breaks in a mobile browser.
3 年多之前 回复
csdnceshi79
python小菜 +1 jQuery is best quality code ever, if you don't use it your a idiot. jQuery is definitely the way to go. </sarcasm>
4 年多之前 回复
csdnceshi71
Memor.の Should be /index.php instead of index.php for the pathname.
4 年多之前 回复
csdnceshi55
~Onlooker It's the same explanation that the one before, but with all the element of the object. Great Answer.
接近 7 年之前 回复

Very Commonly Used top 3 ones are

1. window.location.hostname 
2. window.location.href
3. window.location.pathname

You'll want to use JavaScript's built-in window.location object.

csdnceshi72
谁还没个明天 can confirm at least in the console that window.location.pathname does not retrieve anything after the ?
6 年多之前 回复
csdnceshi71
Memor.の works for me in Firefox, Chrome, and IE. Can you provide a test case of this breaking?
大约 7 年之前 回复
csdnceshi76
斗士狗 this will not return items after '?' in location.
7 年多之前 回复

See purl.js. This will really help and can also be used, depending on jQuery. Use it like this:

$.url().param("yourparam");
// get current URL

$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);

java-script provides many methods to retrieve current URL which is displayed in browser's address bar.

Test URL : http://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in/32942762?rq=1&page=2&tab=active&answertab=votes#32942762

resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);

Function:

var webAddress = {};
var param_values = {};
var protocol = '';
var resourceAddress = {

    fullAddress : function () {
        var addressBar = window.location.href;
        if ( addressBar != '' && addressBar != 'undefined') {
            webAddress[ 'href' ] = addressBar;
        }
    },
    protocol_identifier : function () { resourceAddress.fullAddress();

        protocol = window.location.protocol.replace(':', '');
        if ( protocol != '' && protocol != 'undefined') {
            webAddress[ 'protocol' ] = protocol;
        }
    },
    domain : function () {      resourceAddress.protocol_identifier();

        var domain = window.location.hostname;
        if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
            webAddress[ 'domain' ] = domain;
            var port = window.location.port;
            if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
                if(protocol == 'http') port = '80';
                if(protocol == 'https') port = '443';           
            }
            webAddress[ 'port' ] = port;
        }
    },
    pathname : function () {        resourceAddress.domain();

        var resourcePath = window.location.pathname;
        if ( resourcePath != '' && resourcePath != 'undefined') {
            webAddress[ 'resourcePath' ] = resourcePath;
        }
    },
    params : function () {      resourceAddress.pathname();

        var v_args = location.search.substring(1).split("&");

        if ( v_args != '' && v_args != 'undefined')
        for (var i = 0; i < v_args.length; i++) {
            var pair = v_args[i].split("=");

            if ( typeOfVar( pair ) === 'array' ) {
                param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
            }
        }
        webAddress[ 'params' ] = param_values;
    },
    hash : function () {        resourceAddress.params();

        var fragment = window.location.hash.substring(1);
        if ( fragment != '' && fragment != 'undefined')
            webAddress[ 'hash' ] = fragment;        
    }
};
function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
  • protocol « Web-browsers use Internet Protocol by following some rules for communication between WebHosted Applications and Web Client(Browser). (http = 80, https (SSL) = 443, ftp = 21, etc.)

EX: With default port numbers

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//) « Host is the name given to an end-point(machine on which resource lives) on the Internet. www.stackoverflow.com - DNS IP Address of an Application (OR) localhost:8080 - localhost

Domain names are which you register by the rules and procedures of the Domain Name System(DNS) tree. DNS servers of someone who manages your domain with IP-Address for addressing purposes. In DNS server hierarchy the Root name of an stackoverlfow.com is com.

gTLDs      - com « stackoverflow (OR) in « co « google

Local system you have to maintain domain's which are not PUBLIC in Host Files. localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server). myLocalApplication.com 172.89.23.777

  • (/) « The path gives info about the specific resource within the host that the Web client wants to access
  • (?) « An optional query is to pass a sequence of attribute–value pairs separated by a delimiter(&).
  • (#) « An optional fragment is often an id attribute of a specific element, and web browsers will scroll this element into view.

If parameter has an Epoch ?date=1467708674 then use.

var epochDate = 1467708674; var date = new Date( epochDate );

URL enter image description here


Authentication url with username:password, If usernaem/password contains @ symbol
like:

Username = `my_email@gmail`
password = `Yash@777`

then You need to URL encode the @ as %40. Refer...

http://my_email%40gmail.com:Yash%40777@www.my_site.com

window.location will give you the current URL, and you can extract whatever you want from it...

In jstl we can access current url path using pageContext.request.contextPath, If you want to do a ajax call,

  url = "${pageContext.request.contextPath}" + "/controller/path"

Ex: in the page http://stackoverflow.com/questions/406192 this will give http://stackoverflow.com/controller/path

共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐