zoukankan      html  css  js  c++  java
  • [JS]window.location获取url各项参数详解

    window.location方法后还还可以带href,search等参数,下面我们来看看获取url各项参数的办法。

    URL即:统一资源定位符 (Uniform Resource Locator, URL)
    完整的URL由这几个部分构成:
    scheme://host:port/path?query#fragment
    scheme:通信协议
    常用的http,ftp,maito等


    http://localhost/test/test.htm?id=1
    代码如下 复制代码

    <html>
    <head>
    </head>
    <body>
    <script languge=javascript>
    alert(window.location.pathname); --返回 /test/test.htm
    alert(window.location.search); --返回 ?id=1
    alert(window.location.href); --返回 http://localhost/test/test.htm?id=1
    </script>
    </body>
    </html>

    location对象 含有当前URL的信息. 属性 href 整个URL字符串.
    protocol 含有URL第一部分的字符串,如http:
    host 包含有URL中主机名:端口号部分的字符串.如//www.cenpok.net/server/
    hostname 包含URL中主机名的字符串.如http://www.cenpok.net ;
    port 包含URL中可能存在的端口号字符串.
    pathname URL中"/"以后的部分.如~list/index.htm
    hash "#"号(CGI参数)之后的字符串.
    search "?"号(CGI参数)之后的字符串.


    对于这样一个URL
    代码如下 复制代码

    http://www.php230.com :80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

    我们可以用javascript获得其中的各个部分
    1, window.location.href
    整个URl字符串(在浏览器中就是完整的地址栏)
    本例返回值:
    代码如下 复制代码
    http://www.php230.com :80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

    2,window.location.protocol
    URL 的协议部分
    本例返回值:http:

    3,window.location.host
    URL 的主机部分
    本例返回值:www.php230.com

    4,window.location.port
    URL 的端口部分
    如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
    本例返回值:""

    5,window.location.pathname
    URL 的路径部分(就是文件地址)
    本例返回值:/fisker/post/0703/window.location.html

    6,window.location.search
    查询(参数)部分
    除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
    本例返回值:?ver=1.0&id=6

    7,window.location.hash
    锚点
    本例返回值:#imhere

    项目中的应用:

    //获取页面根目录的下一级目录
    //页面地址:http://192.168.2.98:8020/house-wap/src/main/webapp/user/userCenter.html
    //所获取的地址:http://192.168.1.105:6082/house-wap/
    function getRootPath(){ 
        var pathName = window.location.pathname.substring(1);     
        console.log(pathName);    
         if(pathName == '') {
                 webname=''
             }else{
                 webName=pathName.substring(0, pathName.indexOf('/'))
         };    
        console.log(webName);    
        return window.location.protocol + '//' + window.location.host + '/'+ webName + '/'; 
    }
  • 相关阅读:
    微信小程序 'errcode' => 47003,'errmsg' => 'argument invalid! hint
    微信分账
    Acwing-----1016. 最大上升子序列和
    Acwing-----1012. 友好城市
    Acwing-----482. 合唱队形
    Acwing-----1014. 登山
    Acwing-----1017. 怪盗基德的滑翔翼
    Acwing-----275. 传纸条
    Acwing-----1027. 方格取数
    Acwing-----1018. 最低通行费
  • 原文地址:https://www.cnblogs.com/nicoleyani/p/7027439.html
Copyright © 2011-2022 走看看