我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。


当前回答

要获取路径,可以使用:

console.log('document.location',document.location.href);console.log('location.pathname',window.location.pathname);//仅返回路径console.log('location.href',window.location.href);//返回完整URL

其他回答

使用:window.location.href。

如上所述,更新window.location时,document.URL不会更新。请参阅MDN。

您可以使用以下方法获取带有哈希标记的当前URL位置:

JavaScript:

 // Using href
 var URL = window.location.href;

 // Using path
 var URL = window.location.pathname;

jQuery:

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

在jstl中,我们可以使用pageContext.request.contextPath访问当前的URL路径。如果要进行Ajax调用,请使用以下URL。

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

示例:对于页面http://stackoverflow.com/posts/36577223这将给http://stackoverflow.com/controller/path.

如果您引用的是具有id的特定链接,则此代码可以帮助您。

$(".disapprove").click(function(){
    var id = $(this).attr("id");

    $.ajax({
        url: "<?php echo base_url('index.php/sample/page/"+id+"')?>",
        type: "post",
        success:function()
        {
            alert("The Request has been Disapproved");
            window.location.replace("http://localhost/sample/page/"+id+"");
        }
    });
});

我在这里使用ajax来提交一个id,并使用window.location.replace重定向页面。只需添加一个属性id=“”即可。

打开开发人员工具,在控制台中键入以下内容,然后按Enter键。

window.location

下面是当前页面上的结果截图。

从这里获取您需要的信息。:)