zoukankan      html  css  js  c++  java
  • js获取url参数

    对于这样一个URL
    http://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

    我们可以用javascript获得其中的各个部分
    1、 window.location.href
    整个URl字符串(在浏览器中就是完整的地址栏)
    本例返回值: http://www.x2y2.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.x2y2.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 <src="http://feeds.feedburner.com/~s/fisker?i=http://www.x2y2.com/fisker/post/0703/window.location.html" type="text/javascript" charset="utf-8">

    采用正则表达式获取地址栏参数:
    function GetQueryString(name)
            {
                var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if(r!=null)return  unescape(r[2]);
                return null;
            }
    
    
    // 调用方法
    alert(GetQueryString("参数名1"));
    alert(GetQueryString("参数名2"));
    alert(GetQueryString("参数名3"));

    下面举一个例子:

    若地址栏URL为:abc.html?id=123&url=http://www.maidq.com

    那么,但你用上面的方法去调用:alert(GetQueryString("url"));

    则会弹出一个对话框:内容就是 http://www.maidq.com

    如果用:alert(GetQueryString("id"));那么弹出的内容就是 123 啦;

    当然如果你没有传参数的话,比如你的地址是 abc.html 后面没有参数,那强行输出调用结果有的时候会报错:

    所以我们要加一个判断 ,判断我们请求的参数是否为空,首先把值赋给一个变量:

    var myid=GetQueryString("id");
            if(myid !=null && myid.toString().length>1)
            {
               GetQueryString("id");
            }

    这样就不会报错了!

    摘自:http://www.cnblogs.com/fishtreeyu/archive/2011/02/27/1966178.html

     
  • 相关阅读:
    05--STL序列容器(List和Forward_list)
    04--STL序列容器(Stack和Queue)
    03--STL序列容器(Deque)
    STL迭代器iterator
    02--STL序列容器(Vector)
    C++回顾day03---<string字符串操作>
    C++回顾day03---<输入输出流>
    C++回顾day03---<异常>
    16位结构的CPU,8086给出物理地址的方法
    初识STM32固件库
  • 原文地址:https://www.cnblogs.com/hjbky/p/6961037.html
Copyright © 2011-2022 走看看