在HTML中用JS接收参数

寻技术 Html/CSS / JS脚本 2023年07月22日 65
先介绍一下JS中处理URL的方法:
网址示例:http://localhost/test/test.htm?id=1
 
  • <script languge=javascript>  
  • alert(window.location.pathname);   --返回   /test/test.htm   
  • alert(window.location.search);     --返回   ?id=  
  • alert(window.location.href);       --返回   http://localhost/test/test.htm?id=  
  • </script>
  •  
    ---------------------------------
    location对象 
    含有当前URL的信息. 
    属性 
    href 整个URL字符串. 
    protocol 含有URL第一部分的字符串,如http: 
    host 包含有URL中主机名:端口号部分的字符串.如//www.zzcn.net/server/ 
    hostname 包含URL中主机名的字符串.如http://www.zzcn.net/ ;
    port 包含URL中可能存在的端口号字符串. 
    pathname URL中"/"以后的部分.如~list/index.htm 
    hash "#"号(CGI参数)之后的字符串. 
    search "?"号(CGI参数)之后的字符串.
     

    在HTML中用JS接收参数用到的函数
    function getParameter(param)
    {
    var query = window.location.search;
    var iLen = param.length;
    var iStart = query.indexOf(param);
    if (iStart == -1)
       return "";
    iStart += iLen + 1;
    var iEnd = query.indexOf("&", iStart);
    if (iEnd == -1)
       return query.substring(iStart);

    return query.substring(iStart, iEnd);
    }

    使用的时候:var temp = getParameter("传过来的参数");

    必须得xx.htm?xx=xx这样用啊。呵呵,,,

     

    关闭

    用微信“扫一扫”