PHP中关于href传值和取值的问题

问题:在网页开发过程中或多或少都会遇见如:index.php?id=1&page=2这类的东西,那么我们如何在index.php中把传过来的值获取到呢?


下面是在javascript中获取href传过来的值:

方法一:用正则表达式

function getQueryString(name) {  
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
        var r = window.location.search.substr(1).match(reg);  
        if (r != null) return unescape(r[2]);  
        return null;  
    }
getQueryString("name")//name为去要取的参数,用字符串。

方法二:

function getParam(paramName) {
        paramValue = "", isFound = !1;
        if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {
            arrSource = unescape(this.location.search).substring(1, this.location.search.length).split("&"), i = 0;
            while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
        }
        return paramValue == "" && (paramValue = null), paramValue
    }
    var data = getParam("vote_id");
    alert(data);

第三种带有中文的href

function getUrlParam(name){
        //正则表达式过滤
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        //正则规则
        console.log("reg==="+reg);
        //search:返回URL的查询部分
        console.log("location.search==="+location.search);
        //substr(1):从字符串第一个位置中提取一些字符
        console.log("location.search.substr(1)==="+location.search.substr(1));
        //match():在字符串内检索与正则表达式匹配的指定值,返回一个数组给r
        console.log("window.location.search.substr(1).match(reg)==="+window.location.search.substr(1).match(reg));
        var r = window.location.search.substr(1).match(reg);
        //获取r数组中下标为2的值;(下标从0开始),用decodeURI()进行解码
        console.log("decodeURI(r[2])==="+decodeURI(r[2]));
        console.log("-----------------分隔符------------------------");
        if (r != null) return decodeURI(r[2]); return null;
    }

其他参数获取介绍: 
//设置或获取对象指定的文件名或路径。
alert(window.location.pathname);


//设置或获取整个 URL 为字符串。
alert(window.location.href);

//设置或获取与 URL 关联的端口号码。
alert(window.location.port);

//设置或获取 URL 的协议部分。
alert(window.location.protocol);

//设置或获取 href 属性中在井号“#”后面的分段。
alert(window.location.hash);

//设置或获取 location 或 URL 的 hostname 和 port 号码。
alert(window.location.host);

//设置或获取 href 属性中跟在问号后面的部分。
alert(window.location.search);


下面是在PHP中获取href传过来的值

$vote_id = isset($_GET["vote_id"])?$_GET["vote_id"]:"";
//直接用$_GET方法就可以获得index.php?vote=2,中vote的值
echo $vote_id;//在页面上显示出其值为2;

猜你喜欢

转载自blog.csdn.net/weixin_38420342/article/details/81477068