使用jQuery获取当前URL?

ven*_*lam 1761 javascript url jquery path

我正在使用jQuery.如何获取当前URL的路径并将其分配给变量?

示例网址:

http://localhost/menuname.de?foo=bar&number=0
Run Code Online (Sandbox Code Playgroud)

Rya*_*rty 2413

要获得路径,您可以使用:

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)
Run Code Online (Sandbox Code Playgroud)

  • "我如何在jQuery中使用XYZ"并且答案是普通的javascript非常常见.你可能知道如何用普通的javascript做某事; 但是,由于浏览器的不一致,你可能更喜欢用"jQuery"方式.我记得pre-jQuery或框架我会首先检查浏览器,然后做我想要的一些方法.所以jQuery杀死普通的js ...是的,感谢上帝,但它也使它可用. (198认同)
  • jQuery给Javascript带来了新的生命,而不是杀死它.新的C#/ Java程序员是否理解指针?不,他们需要吗?不是真的,更新的抽象是足够强大的,因为它无关紧要.. (99认同)
  • 位置对象的属性:https://developer.mozilla.org/en/DOM/window.location (78认同)
  • 嗯,... window.location.pathname只获取URL"?" 并且不会像问题中那样得到查询参数. (11认同)
  • 这不适用于完整的网址.例如.对于"https://mail.google.com/mail/u/0/#mbox/13005b79fe72f448",这只会返回/ mail/u/0 (9认同)
  • @dwaynemac:是的,你需要window.location.hash来获取URL的哈希值. (3认同)
  • @flesh大声笑,为什么"指针"总是被用作"过去的日子"的参考......它只是一个指针.在这种情况下更合适的是回到char []并且必须构建一个string.h来处理myVar ="一个非常复杂的对象叫做STRING"; (3认同)

Bor*_*éry 807

在纯jQuery风格:

$(location).attr('href');
Run Code Online (Sandbox Code Playgroud)

location对象还具有其他属性,如host,hash,protocol和pathname.

  • 显然,在jQuery中使用$(location)是不受支持的,并建议不要:http://bugs.jquery.com/ticket/7858 (52认同)
  • @ mc10:"无效"部分适用于支持$(位置)的请求; 不应该使用它. (21认同)
  • @Peter Bug因无效而关闭. (10认同)
  • @HaralanDobrev:您不应该在位置上执行`.attr()`.(1)它不是一个元素,所以`$(location)`最多是阴影,(2)即使它工作,你应该使用`.prop()`来获取属性.`.attr()`用于HTML属性. (8认同)
  • 不需要这个答案,可以更新问题和答案以不使用jquery.原因可以在http://bugs.jquery.com/ticket/7858#comment:4找到 (5认同)

riz*_*zon 461

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>');
Run Code Online (Sandbox Code Playgroud)

这只有在你有jQuery的情况下才有效.例如:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 它与之前的解释相同,但与对象的所有元素相同.很棒的答案. (13认同)
  • [+1 jQuery是有史以来最优质的代码,如果你不使用它是你的白痴.jQuery绝对是要走的路.](http://i.stack.imgur.com/sGhaO.gif)</ sarcasm> (4认同)
  • 对于路径名,应该是`/ index.php`而不是`index.php`. (2认同)
  • 根据http://bugs.jquery.com/ticket/7858,这只是偶然的.此外,`attr`应该只用于DOM对象,用于可以使用HTML属性设置的东西. (2认同)

jlf*_*aux 66

如果您需要URL中存在的哈希参数,window.location.href可能是更好的选择.

window.location.pathname
=> /search

window.location.href 
 => www.website.com/search#race_type=1
Run Code Online (Sandbox Code Playgroud)

  • 我认为@AmitPatel的意思是`window.location.hash` (14认同)
  • 如果有人只需要哈希标记,则可以调用window.location.href (3认同)

cla*_*awr 52

您将需要使用JavaScript的内置window.location对象.

  • 这不会在"?"后返回项目 在位置. (3认同)
  • 至少在控制台中可以确认`window.location.pathname`在`?`之后没有检索到任何东西 (2认同)

小智 44

只需在JavaScript中添加此函数,它将返回当前路径的绝对路径.

function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
Run Code Online (Sandbox Code Playgroud)

我希望这个对你有用.


Gau*_*rav 37

window.location是javascript中的一个对象.它返回以下数据

window.location.host          #returns host
window.location.hostname      #returns hostname
window.location.path          #return path
window.location.href          #returns full current url
window.location.port          #returns the port
window.location.protocol      #returns the protocol
Run Code Online (Sandbox Code Playgroud)

在jquery你可以使用

$(location).attr('host');        #returns host
$(location).attr('hostname');    #returns hostname
$(location).attr('path');        #returns path
$(location).attr('href');        #returns href
$(location).attr('port');        #returns port
$(location).attr('protocol');    #returns protocol
Run Code Online (Sandbox Code Playgroud)


小智 29

这是一个比许多人想象的更复杂的问题.一些浏览器支持内置的JavaScript位置对象以及可通过window.location或访问的相关参数/方法document.location.但是,Internet Explorer(6,7)的不同口味不支持以同样的方式这些方法,( window.location.hrefwindow.location.replace()不支持),所以你必须通过编写条件代码无时无刻手持Internet Explorer的不同访问它们.

所以,如果你有jQuery可用和加载,你也可以使用jQuery(location),因为它解决了这些问题.但是,如果您正在做一个示例 - 通过JavaScript进行一些客户端地理位置重定向(即使用Google Maps API和位置对象方法),那么您可能不想加载整个jQuery库并编写条件代码检查Internet Explorer/Firefox /等的每个版本.

Internet Explorer让前端编码猫不高兴,但jQuery是一盘牛奶.


Mah*_*hat 27

仅限主机名,请使用:

window.location.hostname
Run Code Online (Sandbox Code Playgroud)


Sur*_*ttu 22

这也有效:

var currentURL = window.location.href;
Run Code Online (Sandbox Code Playgroud)


Yas*_*ash 22

java-script提供了许多方法来检索当前URL,该URL显示在浏览器的地址栏中.

测试网址:

http://
stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
?
rq=1&page=2&tab=active&answertab=votes
#
32942762
Run Code Online (Sandbox Code Playgroud)
resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);
Run Code Online (Sandbox Code Playgroud)

功能:

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();
}
Run Code Online (Sandbox Code Playgroud)
  • 协议« Web浏览器通过遵循WebHosted应用程序和Web客户端(浏览器)之间的通信规则来使用Internet协议.(http = 80,https(SSL)= 443,ftp = 21等)

EX:使用默认端口号

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
Run Code Online (Sandbox Code Playgroud)
  • (//)«主机是因特网上给终点(资源所在的机器)的名称.www.stackoverflow.com - 应用程序(OR)localhost的DNS IP地址:8080 - localhost

域名是您通过域名系统(DNS)树的规则和过程注册的.使用IP地址管理您的域以进行寻址的人的DNS服务器.在DNS服务器层次结构中,stackoverlfow.com的根名称为com.

gTLDs      - com « stackoverflow (OR) in « co « google
Run Code Online (Sandbox Code Playgroud)

本地系统您必须维护主机文件中不是PUBLIC的域. localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server). myLocalApplication.com 172.89.23.777

  • (/)«路径提供有关Web客户端要访问的主机内特定资源的信息
  • (?)«可选查询是传递由分隔符(&)分隔的一系列属性 - 值对.
  • (#)«可选片段通常是特定元素的id属性,Web浏览器会将此元素滚动到视图中.

如果参数有Epoch, ?date=1467708674则使用.

var epochDate = 1467708674; var date = new Date( epochDate );
Run Code Online (Sandbox Code Playgroud)

网址 在此输入图像描述


使用用户名:password验证网址,如果usernaem/password包含@符号
,则:

Username = `my_email@gmail`
Password = `Yash@777`
Run Code Online (Sandbox Code Playgroud)

那么你需要对@as 进行URL编码%40.参考...

http://my_email%40gmail.com:Yash%40777@www.my_site.com
Run Code Online (Sandbox Code Playgroud)

encodeURI()(vs)encodeURIComponent()例子

var testURL = "http:my_email@gmail:Yash777@//stackoverflow.com?tab=active&page=1#32942762";

var Uri = "/:@?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
var encodeURIComponent_Str =  encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
/*
 /:@?&=,# +$; (-_.!~*') 
 %2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
*/
Run Code Online (Sandbox Code Playgroud)


dac*_*gen 19

您可以记录window.location并查看所有选项,仅用于URL:

window.location.origin
Run Code Online (Sandbox Code Playgroud)

对于整个路径使用:

window.location.href
Run Code Online (Sandbox Code Playgroud)

还有位置._ _

.host
.hostname
.protocol
.pathname
Run Code Online (Sandbox Code Playgroud)


Riy*_*eed 15

这将使用JavaScript/jQuery返回当前页面的绝对URL.

  • document.URL

  • $("*").context.baseURI

  • location.href


Nis*_*Nis 13

如果有人想要连接URL和哈希标记,请组合两个函数:

var pathname = window.location.pathname + document.location.hash;
Run Code Online (Sandbox Code Playgroud)


Ara*_*yan 12

我有这个去除GET变量.

var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
Run Code Online (Sandbox Code Playgroud)


Moh*_*med 12

您可以使用js本身简单地获取路径,window.location或者location为您提供当前URL的对象

console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);
Run Code Online (Sandbox Code Playgroud)


小智 11

 var currenturl = jQuery(location).attr('href');
Run Code Online (Sandbox Code Playgroud)


Cos*_*sta 11

要从iframe中获取父窗口的URL,请执行以下操作:

$(window.parent.location).attr('href');
Run Code Online (Sandbox Code Playgroud)

注意:仅适用于同一个域


小智 11

以下是使用jQuery和JavaScript获取当前URL的示例:

$(document).ready(function() {

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

    //Pure JavaScript
    var pathname = window.location.pathname;

    // To show it in an alert window
    alert(window.location);
});


$.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
    //alert(json.message);
});
Run Code Online (Sandbox Code Playgroud)


小智 10

以下是可以使用的有用代码片段的示例 - 一些示例使用标准JavaScript函数,并不是特定于jQuery:

请参阅8个有用的jQuery Snippets,用于URL和Querystrings.


Sai*_*ddy 10

使用window.location.href.这将为您提供完整的URL.


ZMR*_*INU 9

window.location将为您提供当前的 URL,您可以从中提取任何内容...


Chu*_*Liu 9

purl.js.这将非常有用,也可以使用,具体取决于jQuery.像这样使用它:

$.url().param("yourparam");
Run Code Online (Sandbox Code Playgroud)


Poo*_*deh 9

通过下面的代码可以在Jquery中获取当前的URL。

$(location).attr('hostname');                //origin URL
$(location).attr('pathname');                // path name
$(location).attr('hash');                    // everything comes after hash
Run Code Online (Sandbox Code Playgroud)


vik*_*hta 8

如果要获取根网站的路径,请使用以下命令:

$(location).attr('href').replace($(location).attr('pathname'),'');
Run Code Online (Sandbox Code Playgroud)


Jon*_*Lin 8

var path = location.pathname返回当前URL的路径(不需要jQuery).使用window.location是可选的.


Nit*_*Pal 8

非常常用的前3个是

1. window.location.hostname 
2. window.location.href
3. window.location.pathname
Run Code Online (Sandbox Code Playgroud)


Sum*_* TG 8

所有浏览器都支持Javascript窗口对象.它定义了浏览器的窗口.

全局对象和函数自动成为窗口对象的一部分.

所有全局变量都是窗口对象属性,所有全局函数都是其方法.

整个HTML文档也是一个窗口属性.

因此,您可以使用window.location对象来获取所有与url相关的属性.

使用Javascript

console.log(window.location.host);     //returns host
console.log(window.location.hostname);    //returns hostname
console.log(window.location.pathname);         //return path
console.log(window.location.href);       //returns full current url
console.log(window.location.port);         //returns the port
console.log(window.location.protocol)     //returns the protocol
Run Code Online (Sandbox Code Playgroud)

JQuery的

console.log("host = "+$(location).attr('host'));
console.log("hostname = "+$(location).attr('hostname'));
console.log("pathname = "+$(location).attr('pathname')); 
console.log("href = "+$(location).attr('href'));   
console.log("port = "+$(location).attr('port'));   
console.log("protocol = "+$(location).attr('protocol'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • 我在您使用“location.path”的地方看到“location.pathname”——这个答案需要更新吗? (2认同)

小智 7

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
Run Code Online (Sandbox Code Playgroud)

  • 你应该在答案上加上一些解释. (2认同)

Aya*_*rty 5

// get current URL

$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);
Run Code Online (Sandbox Code Playgroud)