如何使用jQuery获取当前URL?

2041
我正在使用jQuery。如何获取当前URL的路径并将其分配给一个变量?
示例URL:
http://localhost/menuname.de?foo=bar&number=0

2
你可以在 http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery 上查看如何使用JavaScript和jQuery获取当前URL。 - Rituraj ratan
4
我认为问题应该恢复为询问jQuery,因为无论是否需要jQuery来完成任务,都有一个答案。 - goodeye
1
可能是使用JavaScript获取当前URL?的重复问题。 - vimal1083
4
没有 jQuery 对获取位置的方法;根据 jQuery 的 bug 跟踪器:»它可能起作用,但从未得到支持或文档化。只需使用 document.location.href 更快、更简单、更易于理解。« 换句话说,一些人使用 jQuery 获取位置,但他们依赖于一个 bug,而不是特性。请参见:http://bugs.jquery.com/ticket/7858 - feeela
33个回答

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);
});

10

window.location会给你当前的URL,你可以从中提取你想要的任何内容...


10
使用 window.location.href。这将给你完整的URL

10

在 iframe 中获取父窗口的 URL:

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

注意:仅适用于相同的域名


9

请查看 purl.js。这将真正有所帮助,也可以根据需要使用jQuery。使用方式如下:

$.url().param("yourparam");

9

如果您想获取根站点的路径,请使用以下代码:

$(location).attr('href').replace($(location).attr('pathname'),'');

1
那不应该是 .replace('#.*', '') 吗?不仅要删除井号,还要删除井号后面的所有内容? - Jonas Kölker

9
通过以下代码,您可以在Jquery中获取当前URL。
$(location).attr('hostname');                //origin URL
$(location).attr('pathname');                // path name
$(location).attr('hash');                    // everything comes after hash

8

非常常用的前三个如下:

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

7
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

2
你应该在你的答案中添加一些解释。 - Raptor

3

在jstl中,我们可以使用pageContext.request.contextPath来访问当前URL路径。如果您想要进行AJAX调用,

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

在页面https://dev59.com/6nRC5IYBdhLWcg3wG9To中,这将给出http://stackoverflow.com/controller/path

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接