HTML页面之间的参数传递的局限性

动态网页传递参数比较简单,如果想在HTML之间传递参数就需要一点技巧,摘录两种方法如下:

采用字符串解析的:

/*
*函数功能:从href获得参数
*sHref:   http://www.cscenter.com.cn/arg.htm?arg1=d&arg2=re
*sArgName:arg1, arg2
*return:  the value of arg. d, re
*/
function GetArgsFromHref(sArgName)
{

     var sHref= document.location.href;
    var args  = sHref.split("?");
    var retval = "";
    if(args[0] == sHref) /*参数为空*/
    {
         return retval; /*无需做任何处理*/
    } 
    var str = args[1];
    args = str.split("&");
    for(var i = 0; i < args.length; i ++)
    {
        str = args[i];
        var arg = str.split("=");
        if(arg.length <= 1) continue;
        if(arg[0] == sArgName) retval = arg[1];
    }
    return retval;
}

采用正则表达式的(注意:tmp=rs不是书写错误):

function getQueryString(name){
    var url = document.location.href;
    var rs = new RegExp("(^|)"+name+"=([^\&]*)(\&|$)","gi").exec(url), tmp; 
    if (tmp=rs)
        return tmp[2];
    return ""; 
}

通过解析document.location.href中保存的路径获取传递的参数,在一般情况下没有问题,但如果采用URL Rewrite,情况就不同了。

比如,设置规则将http://jeebook.com/store/category/test/转义为http://jeebook.com/store/index.html?path=test/,这时document.location.href会返回http://jeebook.com/store/category/test/,而不是我们希望的http://jeebook.com/store/index.html?path=test/,于是就无法实现参数传递的效果了

解决办法是在URL Rewrite规则中设置Redirect,URL Rewrite会通过HTTP 301或302重定位新网址,但代价是浏览器中无法显示原来的虚拟路径了。

看来,HTML毕竟还是有局限性的:〉

Leave a Reply

Your email address will not be published. Required fields are marked *